C# enum
In C#, an enum (short for "enumeration") is a set of named constants. Enums are used to define a fixed set of values for a variable or a property, which makes your code more readable and maintainable.
Here's an example of an enum:
public enum DaysOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
In this example, the DaysOfWeek
enum defines seven named constants, one for each day of the week.
To use an enum, you can declare a variable of the enum type and assign one of the named constants to it:
DaysOfWeek today = DaysOfWeek.Tuesday;
You can also use enums in switch statements:
switch (today) { case DaysOfWeek.Monday: Console.WriteLine("It's Monday!"); break; case DaysOfWeek.Tuesday: Console.WriteLine("It's Tuesday!"); break; // ... default: Console.WriteLine("It's not a weekday."); break; }
Enums can also be used as the underlying type for other types, such as byte or int. For example:
public enum Colors : byte { Red = 1, Green = 2, Blue = 3 } Colors myColor = Colors.Green; byte colorValue = (byte)myColor;
In this example, the Colors
enum is defined with an underlying type of byte
, and the myColor
variable is assigned the value of the Green
constant. The colorValue
variable is then assigned the byte value of the myColor
variable using an explicit cast.
Enums are a useful tool for creating more readable and maintainable code, especially when you need to define a fixed set of values for a variable or a property.