C# Enums
Define a group of named constants.
C# Enums
An enum is a special "class" that represents a group of constants (unchangeable/read-only variables).
To create an enum, use the enum keyword (instead of class or interface), and separate the enum items with a comma:
enum Level
{
Low,
Medium,
High
}
You can access enum items with the dot syntax:
Level myVar = Level.Medium;
Enum Values
By default, the first item of an enum has the value 0. The second has the value 1, and so on. To get the integer value from an item, you must explicitly convert the item to an int:
int myNum = (int) Level.Medium; // 1
Enum is often used in switch statements to check for corresponding values.
Examples
Enum in Switch
Using an enum inside a switch statement.
using System;
enum Level
{
Low,
Medium,
High
}
class Program
{
static void Main(string[] args)
{
Level myVar = Level.Medium;
switch(myVar)
{
case Level.Low:
Console.WriteLine("Low level");
break;
case Level.Medium:
Console.WriteLine("Medium level");
break;
case Level.High:
Console.WriteLine("High level");
break;
}
}
}