An enum (short for enumeration) is a special "class" that represents a group of constants (unchangeable/read-only variables). Enums make code more readable and manageable.
enum Days
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
using System;
enum Level
{
Low,
Medium,
High
}
class Program
{
static void Main()
{
Level myLevel = Level.Medium;
Console.WriteLine(myLevel); // Output: Medium
}
}
By default, the first name has the value 0
, the second 1
, and so on.
enum Days
{
Sunday, // 0
Monday, // 1
Tuesday, // 2
Wednesday, // 3
Thursday, // 4
Friday, // 5
Saturday // 6
}
class Program
{
static void Main()
{
Console.WriteLine((int)Days.Tuesday); // Output: 2
}
}
You can assign custom numeric values to enum members.
enum ErrorCode
{
None = 0,
NotFound = 404,
ServerError = 500,
Forbidden = 403
}
class Program
{
static void Main()
{
Console.WriteLine(ErrorCode.NotFound); // Output: NotFound
Console.WriteLine((int)ErrorCode.NotFound); // Output: 404
}
}
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!