We were unable to load Disqus. If you are a moderator please see our troubleshooting guide.

Mistgaetan39 . • 5 years ago

This article is a joke or what ?? 😁
I tested the code using a WPF datagrid, it doesn't work at all !
I can't display my enumeration values "friendly" as you say !
And it's fine to write methods like GetDescription() or GetFriendlyColorEnums(), but where do you call these ??
Oh, nowhere ! So, it's useless of course. So stupid !

Tedebus • 4 years ago

What is wrong with you?
Didn't you see that there are four files and not only one?

FriendlyEnumMethods.cs
EnumExtensionMethods.cs
FriendlyColorsEnum.cs
FriendlyEnumTest.cs

It has to be said that the example is actually quite complex, our friend could invent a simpler one, but it works fine.
What you really need is only one function: GetDescription
The rest only serves the purpose of the examples.

Ultra-simple version: declare this class somewhere:

public static class EnumExtension
{
public static string GetDescription(this Enum GenericEnum)
{
Type genericEnumType = GenericEnum.GetType();
MemberInfo[] memberInfo = genericEnumType.GetMember(GenericEnum.ToString());
if((memberInfo.Length <= 0)) return GenericEnum.ToString();
object[] attribs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
return attribs.Any() ? ((DescriptionAttribute) attribs.ElementAt(0)).Description : GenericEnum.ToString();
}
}

Done!
Let's test it.

1) Create an enum:

private enum FriendlyColorsEnum
{
[Description("Blanched Almond Color")]
BlanchedAlmond = 1,
[Description("Dark Sea Green Color")]
DarkSeaGreen = 2,
[Description("Deep Sky Blue Color")]
DeepSkyBlue = 3,
[Description("Rosy Brown Color")]
RosyBrown = 4
}

2) Somewhere in your code...
Console.WriteLine(FriendlyColorsEnum.DarkSeaGreen.GetDescription());

Result:
>"Dark Sea Green Color"

That's all. Where's the matter?

Kodnot • 6 years ago

Great article! However, I am unsure what changing the GetDescription method to generics accomplishes. Won't one still only be able to use it with Enums, as the methods used inside are Enum-specific? If not, It'd be really nice if the last exercise provided an example of the use of the function on a non-enum type.