In C#, an enum, or enumeration, is a distinct value type that defines a set of named integral constants. Enums provide a way to create named values for a set of related items, making code more readable and self-documenting. Enums are often used to represent a set of predefined values or options.
using System;
namespace EnumExample
{
// Define an enum named Day
public enum Day
{
Sunday, // 0
Monday, // 1
Tuesday, // 2
Wednesday, // 3
Thursday, // 4
Friday, // 5
Saturday // 6
}
class Program
{
static void Main(string[] args)
{
// Assign an enum value
Day today = Day.Wednesday;
// Output the enum value
Console.WriteLine("Today is: " + today); // Outputs: Today is: Wednesday
// Use enums in a switch statement
switch (today)
{
case Day.Monday:
Console.WriteLine("Start of the work week!");
break;
case Day.Wednesday:
Console.WriteLine("Midweek day!");
break;
case Day.Friday:
Console.WriteLine("Almost the weekend!");
break;
case Day.Saturday:
case Day.Sunday:
Console.WriteLine("It's the weekend!");
break;
default:
Console.WriteLine("Just another day.");
break;
}
}
}
}