Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get C# Enum description from value? [duplicate]

Tags:

c#

enums

I have an enum with Description attributes like this:

public enum MyEnum {     Name1 = 1,     [Description("Here is another")]     HereIsAnother = 2,     [Description("Last one")]     LastOne = 3 } 

I found this bit of code for retrieving the description based on an Enum

public static string GetEnumDescription(Enum value) {     FieldInfo fi = value.GetType().GetField(value.ToString());      DescriptionAttribute[] attributes = fi.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];      if (attributes != null && attributes.Any())     {         return attributes.First().Description;     }      return value.ToString(); } 

This allows me to write code like:

var myEnumDescriptions = from MyEnum n in Enum.GetValues(typeof(MyEnum))                          select new { ID = (int)n, Name = Enumerations.GetEnumDescription(n) }; 

What I want to do is if I know the enum value (e.g. 1) - how can I retrieve the description? In other words, how can I convert an integer into an "Enum value" to pass to my GetDescription method?

like image 326
davekaro Avatar asked Apr 16 '10 01:04

davekaro


People also ask

What is %s in C?

%s is for string %d is for decimal (or int) %c is for character.


1 Answers

int value = 1; string description = Enumerations.GetEnumDescription((MyEnum)value); 

The default underlying data type for an enum in C# is an int, you can just cast it.

like image 75
Nicholas Piasecki Avatar answered Sep 30 '22 19:09

Nicholas Piasecki