C# Enums
An enum (enumeration) is a special type that represents a fixed set of named constants, making code more readable than using plain numbers. For example, an enum could represent days of the week or order statuses.
By default, enum values are backed by integers starting at 0, but you can assign specific values explicitly if needed.
enum Name {
Value1, Value2, Value3
}Defining and using enums
An enum is declared with the `enum` keyword and a list of named values, like `enum Day { Monday, Tuesday, Wednesday }`. You access a value using the enum name and a dot, like `Day.Monday`.
Underlying values
Each enum member has an underlying int value, starting at 0 by default. You can cast between an enum and its int value, and assign custom starting values explicitly.
using System;
enum Day { Monday, Tuesday, Wednesday }
class Program {
static void Main() {
Day today = Day.Tuesday;
Console.WriteLine(today);
}
}Tuesdaytoday stores an enum value, which prints as its named label rather than a number.
using System;
enum Day { Monday, Tuesday, Wednesday }
class Program {
static void Main() {
Day today = Day.Wednesday;
int value = (int)today;
Console.WriteLine(value);
}
}2Casting an enum to int reveals its underlying numeric value, starting at 0 by default.
Key points
- An enum defines a fixed set of named constant values.
- Enum values are backed by integers, starting at 0 by default.
- Enums make code more readable than using raw numbers.
- You can cast between an enum and its underlying int type.
