Enumerations
Enumerations, or enums for short, are a type in C# that allows you to define a set of named constants. Enums make your code more readable and maintainable by providing a way to represent a fixed set of values with descriptive names.
Here's an example of how to define an enum in C#:
enum DaysOfWeek
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
In this example, we define an enum named DaysOfWeek that contains seven named constants, one for each day of the week.
You can use enums in your code by referencing the enum type and one of its named constants. For example:
DaysOfWeek today = DaysOfWeek.Wednesday;
In this example, we declare a variable named today
of type DaysOfWeek
and assign it the value DaysOfWeek.Wednesday
.
You can also use enums in switch statements, which can make your code more readable than using integer constants:
switch (today)
{
case DaysOfWeek.Monday:
Console.WriteLine("Today is Monday");
break;
case DaysOfWeek.Tuesday:
Console.WriteLine("Today is Tuesday");
break;
// ...
default:
Console.WriteLine("Unknown day");
break;
}
Enums can also have an underlying type, which specifies the numeric type used to represent the named constants. For example, you can define an enum with an underlying type of int like this:
enum ErrorCode : int
{
None = 0,
NotFound = 404,
ServerError = 500
}
In this example, we define an enum named ErrorCode with an underlying type of int, and we assign specific integer values to each named constant.
Enums are a powerful feature in C# that can help you write more readable and maintainable code. By defining a set of named constants with descriptive names, you can make your code easier to understand and modify:
Comments
Post a Comment