This is my enum:
public enum DocumentTypes
{
[EnumMember]
TYPE_1 = 1,
[EnumMember]
TYPE_2 = 2,
[EnumMember]
TYPE_3 = 3,
[EnumMember]
TYPE_4 = 4,
[EnumMember]
TYPE_5 = 5,
[EnumMember]
TYPE_6 = 6,
[EnumMember]
TYPE_7 = 7,
[EnumMember]
TYPE_8 = 12
}
If I want to obtain ‘TYPE_8’, if I only have 12, is there a way to get the enum value?
I tried this:
((DocumentTypes[])(Enum.GetValues(typeof(DocumentTypes))))[Convert.ToInt32("3")].ToString()
which returns a value of ‘TYPE_4’
This gives will also handle invalid values trying to be used, without the internal exception being thrown
You can also replace the string with DocumentTypes, ie
And for the bonus point, here is how to add a custom string to an enum (copied from this SO answer)
Then add an extenstion method somewhere
Then you can use:
Which will retrive the Description attribute value.
Edit – updated code
Here is a new version of the extension method that does’t need to know the type of the Enum before hand.