Enums and Constants
Enumerations, or 'enums' as they are commonly known, are a powerful feature in C# that allow you to assign names to integral values, making your code more readable and maintainable. They are especially useful when you want to represent a set of named constants in your program.
Download this lesson as a Polyglot Notebook to open in Visual Studio Code, or open directly in your web browser with Binder.
An enum is a type that consists of a set of named constants that are associated with integral (numeric) values. By defining and using enum types we can make our code more human readable and constrain the potential values that can be assigned to a variable. Let's start with defining an enum type of the various suits in a standard deck of playing cards:
public enum Suit { Clubs = 0, Diamonds = 1, Hearts = 2, Spades = 3 }
The enum is defined with a scope, public in this case, the keyword enum and a name for the type. This is followed by a collection of the enumerable values inside of a pair of curly braces { }
with their values and optionally a value to assign. When values are omitted, the assigned values start with zero and count upwards.
We can declare a variable to be of an enum type, and assign a value with this clear syntax:
Suit myCardsSuit = Suit.Clubs;
The underlying value of the myCardsSuit
variable is a 0
but we can easily read what the value is. The following code is invalid and will result in an error:
Suit yourCardsSuit = Suit.Hammers;
There is no Hammers
value in the Suit
enum, so this statement is invalid.
Flags
Sometime we would like to store 2 or more possible values using an enum type. Traditionally, we would do this with binary values (1,2,4,8,16...) and summing those values to represent a total numeric value. With enums, we can activate a similar capability that allows a single enum variable to represent multiple values. Let's look at scheduling a recurring game night on several nights of the week. We can define as a ScheduleDayOfWeek enum like this:
[Flags] public enum ScheduleDayOfWeek { Sunday = 1, Monday = 2, Tuesday = 4, Wednesday = 8, Thursday = 16, Friday = 32, Saturday = 64 }
These initial values correspond to the powers of 2 and with the [Flags]
attribute decorator above the type we can use these values together in our code. Perhaps we'd like to schedule game night on Friday and Saturday nights. We can add these values together using the |
OR operator like in this code:
var gameNights = ScheduleDayOfWeek.Friday | ScheduleDayOfWeek.Saturday;
display(gameNights);
Now we have 1 variable that represents both nights. We can redefine the type with extra values that are a convenience and show the combination of values:
[Flags] public enum ScheduleDayOfWeek { Sunday = 1, Monday = 2, Tuesday = 4, Wednesday = 8, Thursday = 16, Friday = 32, Saturday = 64, Weekends = 65, Weekdays = 62, Everyday = 127 } var workWeek = ScheduleDayOfWeek.Weekdays; display(workWeek);
ScheduleDayOfWeek
is a Flags decorated enum, so we can use the commas to separate values and the sum of values to represent a set of values. This type of combination doesn't work with the Suit
enum we defined earlier.
var suitsInHand = Suit.Clubs | Suit.Diamonds?| Suit.Hearts;
That's... not the value we expected because it is the sum of the integral values underlying the three values combined.
We can also convert from string values to the enum value using the Parse
method. This allows us to read either a text or numeric value and convert it to the expected enum values. Consider these statements:
display(Enum.Parse(typeof(ScheduleDayOfWeek), "Monday")); display(Enum.Parse<ScheduleDayOfWeek>("Tuesday")); display(Enum.Parse<ScheduleDayOfWeek>("8")); display(Enum.Parse<ScheduleDayOfWeek>("Thursday,Friday")); display(Enum.Parse<ScheduleDayOfWeek>("65"));
Finally, we can also use the logical AND operator &
to check if a value is part of the assigned value.
display(ScheduleDayOfWeek.Weekends & ScheduleDayOfWeek.Friday); display(ScheduleDayOfWeek.Weekdays & ScheduleDayOfWeek.Friday);
Constants
Let's also touch briefly on the topic of constants. A constant is a variable that is declared at coding time but can never be changed. This value is constant and is a good way to remove the practice of "magic values" in code where you might be testing or comparing to a fixed value.
A constant is declared similar to a normal variable, but with the addition of the const
keyword. I could have code that looks like the following:
if (DateTime.Now.Hour <= 6) { ? display("You should still be sleeping, it's before 6!"); } else { ? display("You should be awake, it's after 6"); }
That 6 in the test appears in the descriptions, and if my wake up hour changes, all of that code and the messages need to be re-written. By introducing a constant we can make this easier to read and re-use the value:
const int WakeUpHour = 6; if (DateTime.Now.Hour <= WakeUpHour) { ? display($"You should still be sleeping, it's before {WakeUpHour}!"); } else { ? display($"You should be awake, it's after {WakeUpHour}"); }