Enumerations, or enums, in C# are a powerful feature that allows you to define a named set of named constants representing integral values. Enumerations make your code more readable and maintainable by providing a way to give friendly names to numeric values. Here's a tutorial on how to use enumerations in C#.
1. Creating Enumerations:
To create an enumeration, use the enum
keyword followed by the name of the enumeration. Here's a simple example:
In this example, DaysOfWeek
is an enumeration representing the days of the week. By default, the values of the enum start at 0 and increment by 1.
2. Using Enumerations:
You can use enumerations in your code just like any other data type. Here's an example of how to declare a variable with an enumeration type:
DaysOfWeek today = DaysOfWeek.Wednesday;
3. Underlying Type:
By default, enums are of type int
, but you can explicitly specify another integral type if needed:
In this example, Status
is an enumeration with an underlying type of byte
.
4. Accessing Enum Values:
You can access the underlying numeric value of an enum using casting:
int dayValue = (int)DaysOfWeek.Monday;
5. Looping Through Enum Values:
You can iterate through all values of an enumeration using the Enum.GetValues
method:
foreach (DaysOfWeek day in Enum.GetValues(typeof(DaysOfWeek))){Console.WriteLine(day);}
6. Parsing Enum Values:
You can convert a string to an enum using the Enum.Parse
method:
string dayString = "Wednesday";DaysOfWeek day = (DaysOfWeek)Enum.Parse(typeof(DaysOfWeek), dayString);
7. Checking if a Value is Defined:
You can check if a value is defined in an enumeration using the Enum.IsDefined
method:
bool isDefined = Enum.IsDefined(typeof(DaysOfWeek), "Sunday");
8. Flags Attribute:
If you need to combine multiple enum values, you can use the Flags
attribute:
[Flags]public enum Permissions{Read = 1,Write = 2,Execute = 4}
With the Flags
attribute, you can use bitwise operations to combine enum values:
Permissions myPermissions = Permissions.Read | Permissions.Write;
This is a basic overview of using enums in C#. Enumerations are a simple yet powerful tool for improving code readability and maintainability by giving meaningful names to numeric values.