C# Enum Type
An enumeration (enum) is a distinct value type that defines a set of named integral constants. Enums make your code more readable and maintainable by giving meaningful names to a set of related values.
Here's a basic example of defining and using an enum in C#.
using System;
public class Program
{
// Define an enumeration named 'Days'.
public enum Days
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
public static void Main()
{
// Assign a value from the 'Days' enum.
Days today = Days.Wednesday;
// Output the value of the enum variable.
Console.WriteLine("Today is: " + today);
// Enum values can be compared using equality operators.
if (today == Days.Wednesday)
{
Console.WriteLine("It's the middle of the week!");
}
}
}
In this example, the Days
enum is defined with seven named constants representing the days of the week. An enum variable today
is then declared and assigned the value Days.Wednesday
.
Finally, the program outputs the value of the enum variable and checks if it's equal to Days.Wednesday
.
Enums can also have an underlying type (e.g., byte, int) and can be used in switch statements, making them a powerful tool for writing more expressive and self-documenting code.
public enum Season
{
Spring,
Summer,
Autumn,
Winter
}
public class Program
{
public static void Main()
{
Season currentSeason = Season.Summer;
switch (currentSeason)
{
case Season.Spring:
Console.WriteLine("It's spring!");
break;
case Season.Summer:
Console.WriteLine("It's summer!");
break;
case Season.Autumn:
Console.WriteLine("It's autumn!");
break;
case Season.Winter:
Console.WriteLine("It's winter!");
break;
default:
Console.WriteLine("Unknown season");
break;
}
}
}
In this example, the Season
enum is used to represent the four seasons, and a switch statement is employed to handle different cases based on the current season.