Enumerating an enum in C# involves using the Enum.GetValues
method, which returns an array of the values in the specified enumeration. This method can be particularly useful when you need to iterate over all the values of an enum, for instance, to display them or perform certain actions based on each value. By using a foreach
loop, you can easily enumerate through the enum values, making your code more flexible and reducing the need for hardcoding specific enum values.
Using Enum.GetValues
Basic Example:
To enumerate an enum, use Enum.GetValues
:
public enum Colors
{
Red,
Green,
Blue,
Yellow
}
foreach (Colors color in Enum.GetValues(typeof(Colors)))
{
Console.WriteLine(color);
}
Enum.GetValues(typeof(Colors))
: Retrieves an array of all enum values.- The
foreach
loop iterates over each value and prints it.
Output:
Red
Green
Blue
Yellow
Detailed Example with Flags
Enum with Flags:
Enumerating an enum with the [Flags]
attribute involves similar steps:
[Flags]
public enum FileAccess
{
Read = 1,
Write = 2,
Execute = 4,
ReadWrite = Read | Write
}
foreach (FileAccess access in Enum.GetValues(typeof(FileAccess)))
{
Console.WriteLine(access);
}
- This example demonstrates how to handle enums that use the
[Flags]
attribute.
Output:
Read
Write
Execute
ReadWrite
Using Enum.GetNames
Retrieving Names:
If you need to get the names of the enum values, use Enum.GetNames
:
public enum Days
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
foreach (string day in Enum.GetNames(typeof(Days)))
{
Console.WriteLine(day);
}
Enum.GetNames(typeof(Days))
: Retrieves an array of the names of the enum values.
Output:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Using Enum.GetName with Value
Getting Name for a Specific Value:
To get the name corresponding to a specific value:
public enum Status
{
Pending = 1,
Approved = 2,
Rejected = 3
}
int value = 2;
string name = Enum.GetName(typeof(Status), value);
Console.WriteLine(name);
Enum.GetName(typeof(Status), value)
: Returns the name of the enum value.
Output:
Approved
Combining Values and Names
Combining Values and Names:
You can combine values and names for more detailed output:
public enum Sizes
{
Small,
Medium,
Large
}
foreach (Sizes size in Enum.GetValues(typeof(Sizes)))
{
Console.WriteLine($"Name: {size}, Value: {(int)size}");
}
- This example combines enum names with their corresponding integer values.
Output:
Name: Small, Value: 0
Name: Medium, Value: 1
Name: Large, Value: 2
Using LINQ for Advanced Enumeration
LINQ Example:
For more complex operations, use LINQ:
public enum Levels
{
Low,
Medium,
High
}
var levels = Enum.GetValues(typeof(Levels)).Cast();
var highLevel = levels.FirstOrDefault(l => l == Levels.High);
Console.WriteLine(highLevel);
- This example uses LINQ to find and print a specific enum value.
Output:
High
Validating Enum Values
Validating Values:
To validate if a value exists in an enum:
public enum Fruits
{
Apple,
Banana,
Cherry
}
bool isValid = Enum.IsDefined(typeof(Fruits), "Banana");
Console.WriteLine(isValid);
Enum.IsDefined(typeof(Fruits), "Banana")
: Checks if "Banana" is a defined enum value.
Output:
True
Parsing Enums
Parsing String to Enum:
Convert a string to an enum value using Enum.Parse
:
public enum Directions
{
North,
South,
East,
West
}
string directionString = "East";
Directions direction = (Directions)Enum.Parse(typeof(Directions), directionString);
Console.WriteLine(direction);
Enum.Parse(typeof(Directions), directionString)
: Converts the string "East" to the corresponding enum value.
Output:
East
Enum with Attributes
Custom Attributes:
Apply custom attributes and retrieve them using reflection:
public enum Animals
{
[Description("Man's best friend")]
Dog,
[Description("Graceful and independent")]
Cat
}
foreach (Animals animal in Enum.GetValues(typeof(Animals)))
{
var fieldInfo = animal.GetType().GetField(animal.ToString());
var descriptionAttributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (descriptionAttributes.Any())
{
Console.WriteLine($"{animal}: {descriptionAttributes[0].Description}");
}
}
- This example demonstrates using custom attributes and reflection to enumerate enums with descriptions.
Output:
Dog: Man's best friend
Cat: Graceful and independent
Summary
Enumerating an enum in C# is a powerful feature that can be achieved using the Enum.GetValues
and Enum.GetNames
methods, providing flexibility to iterate over all enum values or their names. Combining these methods with LINQ, validation techniques, parsing, and custom attributes enhances the versatility and maintainability of your code. These practices allow for clean, efficient, and understandable code when working with enums in various applications.