C# Enums
An enum (short for "enumeration") is a special kind of type in C# that lets you give friendly names to a set of related constant values. Instead of scattering magic numbers like 0, 1, and 2 through your code, you can define readable names such as Monday, Tuesday, and Wednesday. Enums make your code clearer, safer, and much easier to read.
Creating an Enum
You declare an enum with the enum keyword, followed by a name and a list of its possible values (called members) inside curly braces. Enum members are separated by commas. By convention, enum names and their members use PascalCase.
Defining and using an enum
using System;
class Program
{
enum Level
{
Low,
Medium,
High
}
static void Main()
{
Level myLevel = Level.Medium;
Console.WriteLine(myLevel);
}
}
// Output:
// MediumBehind the scenes, each enum member is stored as an integer. By default the first member is 0, the next is 1, and so on. So Low is 0, Medium is 1, and High is 2. You can see the underlying number by casting the enum value to an int.
Enums are numbers underneath
using System;
class Program
{
enum Level { Low, Medium, High }
static void Main()
{
Level myLevel = Level.High;
int number = (int)myLevel;
Console.WriteLine(number);
Console.WriteLine((int)Level.Low);
}
}
// Output:
// 2
// 0Assigning Your Own Values
You are not stuck with the default numbering. You can assign specific integer values to any member. This is handy when the numbers have real meaning, such as HTTP status codes or point values. Members that follow a manually assigned value continue counting up from it.
Custom enum values
using System;
class Program
{
enum StatusCode
{
Ok = 200,
NotFound = 404,
ServerError = 500
}
static void Main()
{
StatusCode result = StatusCode.NotFound;
Console.WriteLine($"{result} = {(int)result}");
}
}
// Output:
// NotFound = 404Enums in a Switch Statement
Enums pair perfectly with switch statements. Because the set of values is fixed and named, each case reads like plain English, which makes decision logic easy to follow.
Choosing behavior based on an enum
using System;
class Program
{
enum Level { Low, Medium, High }
static void Main()
{
Level myLevel = Level.Medium;
switch (myLevel)
{
case Level.Low:
Console.WriteLine("Take it easy.");
break;
case Level.Medium:
Console.WriteLine("Staying balanced.");
break;
case Level.High:
Console.WriteLine("Full speed ahead!");
break;
}
}
}
// Output:
// Staying balanced.Enum Members Overview
Exercise: C# Enums
What is the default underlying numeric type of a C# enum?