Defining and Using Enums
Create enums with explicit and implicit values.
What is an Enum?
An enum is a named set of related constants. It makes code readable by replacing magic numbers with meaningful names.
using System;
enum Direction { North, East, South, West }
class Program {
static void Main() {
Direction d = Direction.East;
Console.WriteLine(d);
}
}Declaring an Enum
You declare an enum with the enum keyword and list its members. By default the first is 0, the next 1, and so on.
using System;
enum Day { Mon, Tue, Wed }
class Program {
static void Main() {
Console.WriteLine((int)Day.Mon);
Console.WriteLine((int)Day.Wed);
}
}All lessons in this course
- Defining and Using Enums
- Flags Enums and Bitwise Combinations
- Enum Conversions and Parsing
- Iterating Enum Values