Take a look at this enum
extension method for getting the Description
attribute:
public static string GetDescription(this Enum enumValue)
{
var memberInfo = enumValue.GetType().GetMember(enumValue.ToString());
if (memberInfo.Length < 1)
return null;
var attributes = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes.Length > 0 ? ((DescriptionAttribute)attributes[0]).Description : enumValue.ToString();
}
And an example enum
with Description
attributes:
public enum Colors
{
[Description("Navy Blue")]
Blue,
[Description("Lime Green")]
Green
}
And finally the usage of the extension method:
var blue = Colors.Blue;
Console.WriteLine(blue.GetDescription());
// Console output: Navy Blue
My question is, when it comes to enum
s, is the if (memberInfo.Length < 1)
check necessary? Would the returned array from GetMember()
ever be empty for an enum
? I know you can declare an empty enum
like this:
public enum Colors
{
}
But I don't know if you can even create a variable of type Colors
then...
var green = Colors. // What goes here?
I would like to remove the if (memberInfo.Length < 1)
check, but I don't want to do it if it will cause problems later (I can't think of a reason I'd ever need an empty enum
, but other developers will probably use the GetDescription()
extension method).
You can create a variable of type Colors
even if no value is defined:
public enum Colors { }
var color2 = (Colors)100; // with casting
Colors color2 = default; // default value '0'