Enums
Enums, short for “enumerations,” are a distinct value type in C# that allows you to define a set of named constants. They provide a convenient way to work with related constants, enhancing the readability and maintainability of your code. Enums are particularly useful when you have a fixed set of related values, such as days of the week, months of the year, or directions.
Basics of Enums
- Definition: Enums are defined using the ‘enum’ keyword, followed by the name of the enumeration and a list of named constants enclosed in curly braces.
- Underlying Type: By default, the underlying type of each enum member is ‘int’, though you can specify a different numeric type (such as ‘byte’, ‘short’, or ‘long’).
- Default Values: The first enum member is assigned the value 0 by default, and subsequent members are incremented by one. You can also assign specific values to enum members if desired.
Example
using System;
// Define an enum for days of the week
enum DayOfWeek
{
Sunday, // 0
Monday, // 1
Tuesday, // 2
Wednesday, // 3
Thursday, // 4
Friday, // 5
Saturday // 6
}
class Program
{
static void Main()
{
// Declare a variable of type DayOfWeek
DayOfWeek today = DayOfWeek.Monday;
// Display the value of the enum variable
Console.WriteLine($"Today is: {today}");
// Use a switch statement with the enum
switch (today)
{
case DayOfWeek.Sunday:
Console.WriteLine("Relax, it's Sunday!");
break;
case DayOfWeek.Monday:
Console.WriteLine("Back to work, it's Monday!");
break;
case DayOfWeek.Tuesday:
Console.WriteLine("It's Tuesday, keep going!");
break;
case DayOfWeek.Wednesday:
Console.WriteLine("It's Wednesday, halfway there!");
break;
case DayOfWeek.Thursday:
Console.WriteLine("It's Thursday, almost the weekend!");
break;
case DayOfWeek.Friday:
Console.WriteLine("It's Friday, time to wrap up the week!");
break;
case DayOfWeek.Saturday:
Console.WriteLine("Enjoy your Saturday!");
break;
default:
Console.WriteLine("Invalid day!");
break;
}
// Convert a string to DayOfWeek enum
string dayString = "Friday";
if (Enum.TryParse(dayString, out DayOfWeek parsedDay))
{
Console.WriteLine($"Parsed {dayString} as: {parsedDay}");
}
else
{
Console.WriteLine($"Failed to parse {dayString}");
}
}
}
Benefits of Using Enums
- Readability: Enums provide meaningful names for sets of related values, making your code more understandable.
- Type Safety: Enums are strongly typed, reducing the chance of invalid values being assigned.
- Maintainability: Enums centralize related constants, making it easier to manage and update them.
- Switch Statements: Enums work well with switch statements, providing a clear structure for handling different cases.
