Enumerations
Explore how to define and use enumerations in C# to represent sets of related constants like days of the week. Learn the syntax, assign values, and apply enums for type safety and clearer code, enabling you to handle specific states and parameters effectively in your programs.
We'll cover the following...
C# allows us to create enumerations in addition to primitive data types. An enumeration in C# represents a collection of logically related constants.
Suppose a method needs to accept a day of the week as a parameter. We have several options:
We could accept a string value (like
"Monday").We could accept an integer that represents the day of the week (like
2).We could use enumerations.
Enumerations definition
We can create an enumeration containing all days of the week to ensure the caller selects a valid, predefined constant.
An enumeration is declared using the enum keyword:
enum WeekDay{}
Line 1: Uses the
enumkeyword to define a new type namedWeekDay.
We can optionally specify the underlying type of the enumeration, which must be an integral type. If the type is omitted, int is used by default.
enum WeekDay : short{}
Line 1: Declares the
WeekDayenum and specifiesshortas the underlying type.
The body of the enumeration consists of comma-separated constants:
enum WeekDay : short{Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday}
Lines 3–9: List the named constants representing the days of the week.
Each element of the enumeration is assigned an integer value, with the first element valued at 0, the second element 1, and so on.
We can specify the elements’ values by indicating the first value:
enum WeekDay : short{Monday = 1,Tuesday, // 2Wednesday, // 3Thursday, // 4Friday, // 5Saturday, // 6Sunday // 7}
Line 3: Explicitly assigns
1toMonday. Subsequent members increment automatically.
We can also specify the values of all constants:
enum YearCount{Year = 1,Decade = 10,Century = 100,Millennium = 1000}
Lines 4–5: Assign the value
2toRockandAlternative.Line 6: Assigns the value of
Classic(which is 1) toOld.
Enumerations usage
Each enum defines a new data type. This means that we can declare a variable of this type and use it. Let’s try it out with an example:
Line 2: Declares a variable
currentDayof typeWeekDayand assigns it the constantWednesday.Line 4: Prints the name of the constant (“Wednesday”) to the console.
Lines 7–16: Defines the
WeekDayenumeration at the bottom of the file.
Note: It’s good practice to have a separate file for each type we create. In a real-world application, the WeekDay enum would likely reside in its own file (e.g., WeekDay.cs) to keep the codebase organized.
After creating an enumeration type, we can create a variable of this type and assign it a value. Note that we can only assign one enumeration constant to this variable. Although these constants are backed by integers internally, we cannot assign a number directly to an enumeration variable.
Line 2: Represents the attempted assignment. If uncommented, this would cause a compilation error because C# enforces type safety.
The error hints that we need an explicit cast. When we print the variable of the enum type, we get the string with the constant’s name instead of its numeric value. If we need the numeric value, we can use an explicit cast:
Line 3: Uses
(int)to explicitly cast theWeekDayvalue to its integer representation. This prints "2" (since Monday is 0, Tuesday is 1, Wednesday is 2).
Enumerations in practice
We typically use enumerations to represent state, performing different actions based on that state. We could use enums as parameters of methods when we need to have only specific input for a method.
It’s good practice to have a separate file for each type we create. That’s why we’ve defined our enumeration inside a different file here.
Consider the following example:
Line 1: Creates a variable and passes it to a method.
Line 6: Defines a local method
PrintMessageOfTheDaythat takes the enum as a parameter.Line 9: Uses a
switchstatement to execute different logic based on the enum value.
Note: When using top-level statements in a single file, we must write our executable code (like assignments and printing) before defining the enum.