Enum values
2023-03-16 C# Enum GetValues AttributeC# language provides nice way to define enumerated values. You can build group of them like this
enum Style
{
Big,
Small,
Perfect
};
There is underlying type (by default it is int
) and values start with default zero and each following has incremented value. Specific values can be also assigned. The enum can be used as type for parameters, properties, or variables
Style style = Style.Big;
if(style == Style.Perfect) {
// do something
}
Now something more advanced - it is possible to enumerate all values from the enum with Enum.GetValues
like this
foreach(Style item in Enum.GetValues(typeof(Style)).Cast<Style>()) {
Console.WriteLine($"{(int)item} = {item.ToString()}");
}
It prints out underlying value and its name
0 = Big
1 = Small
2 = Perfect
Sometimes it can be also very useful to attach a description to each value, so we can have good identifier in the code, but for output outside it can be nicer and easier to read
public enum Style
{
[Description("Really big")]
Big,
[Description("Really small")]
Small,
[Description("Great fit")]
Perfect
};
With a small extension method
public static class EnumExtensions
{
public static string Description(this Enum value)
{
if (value == null)
return "";
// Find description attribute
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute attribute = fi.GetCustomAttribute<DescriptionAttribute>();
// Return attribute description or call basic ToString method
if (attribute != null)
return attribute.Description;
else
return value.ToString();
}
}
it is possible to get descriptions like this
Style.Big.Description() // Gets: Really big
Style.Small.Description() // Gets: Really small
Style.Perfect.Description() // Gets: Great fit
It is also nice illustration of attribute usage for attaching extra information to C# structures.