Enumeration data type in C#

In C#, an enumeration, often referred to as an enum, is a user-defined data type that consists of a set of named constants. Enums provide a way to define a collection of related values, making the code more readable and maintainable.

Here's an example that demonstrates the usage of an enum in C#:


enum DaysOfWeek
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

// Using the enum
DaysOfWeek today = DaysOfWeek.Monday;
Console.WriteLine(today);  // Output: Monday

if (today == DaysOfWeek.Saturday || today == DaysOfWeek.Sunday)
{
    Console.WriteLine("It's the weekend!");
}
else
{
    Console.WriteLine("It's a weekday.");
}

In the example above, we define an enum named DaysOfWeek with a list of constants representing the days of the week. Each constant is implicitly assigned an integer value starting from 0 (Monday) to 6 (Sunday).

We then declare a variable named today of type DaysOfWeek and assign it the value DaysOfWeek.Monday. We can compare enum values using the == operator and perform conditional checks based on the enum values.

Enums are commonly used to represent a set of mutually exclusive options or states. They provide a more expressive and readable way to work with predefined sets of values. Enums can also be used as the underlying type for properties, method parameters, and return types, allowing for strong typing and clarity in code.

Enums can also be explicitly assigned specific values if desired, using the assignment operator (=). Here's an example:


enum Status
{
    Active = 1,
    Inactive = 2,
    Suspended = 3
}

In this example, the Status enum has three constants with explicitly assigned values.

Enums in C# provide a convenient and concise way to work with a predefined set of related values, improving code readability and maintainability.