Why am I not finding any Enumerations class in the .Net framework?
– Spencer RuportDec 26 '13 at 17:56

70

The Enumerations class is something that the person who asked the question wrote himself, and the GetEnumDescription() function is in the question.
– Nicholas PiaseckiDec 29 '13 at 17:03

11

A better approach could be to use extension method instead. To do this, convert Enumerations.GetEnumDescription 's Enum value parameter to this Enum value and then call it like string description = ((MyEnum)value).GetEnumDescription()
– gkcNov 25 '14 at 14:09

@davekaro: It casts the int to MyEnum - but you wouldn't be able to call it with any non-enum, including an "Enum" reference. Basically it's like your code, but with some generics magic.
– Jon SkeetApr 16 '10 at 13:06

@AlexZhukovskiy: I suspect so, although I haven't tried. You may need to use import="dnxcore450" or whatever. When .NET Core 1.0 ships, I'll try to remember to update the package to ensure it works with netstandard1.0.
– Jon SkeetMay 27 '16 at 10:48

string classDesc = myInstance.SomeProperty.DescriptionAttr(); That will not work! Let say you have class Test { public int TestInt {get; set;} }. So if you will call new Test().TestInt.DescriptionAttr() you will get null reference exception - 0.GetType().GetField("0")
– VladimirsDec 12 '13 at 13:34

You can't easily do this in a generic way: you can only convert an integer to a specific type of enum. As Nicholas has shown, this is a trivial cast if you only care about one kind of enum, but if you want to write a generic method that can handle different kinds of enums, things get a bit more complicated. You want a method along the lines of:

but this results in a compiler error that "int can't be converted to TEnum" (and if you work around this, that "TEnum can't be converted to Enum"). So you need to fool the compiler by inserting casts to object:

How is "GetEnumDescription<MyEnum>(1);" any better than GetEnumDescription((MyEnum)1); ?
– davekaroApr 16 '10 at 2:09

@davekaro: Implemented like this, it's not all that much better, but a more robust implementation based on generics could do this without the explicit cast, so you don't risk unhandled exceptions if the number doesn't actually match any of the enum values.
– AaronaughtApr 16 '10 at 2:15

Interesting. Just to clarify for future readers: One is not going to get an unhandled exception on an explicit cast if the number doesn't match one of the enum values (you could say "MyEnum value = (MyEnum)5;" and that line will execute just fine, but you would bomb in the first line of GetEnumDescription() as implemented in the original question (because GetField() will return null as it can find no matching field with that value). (To guard against that, we'd need to check Enum.IsDefined() first and return null or an empty string, or just throw an ArgumentOutOfRangeException ourselves.)
– Nicholas PiaseckiApr 16 '10 at 2:48