Retrieve value of Enum based on index - c#
You can directly cast it:
int value = 12;
DocumentTypes dt = (DocumentTypes)value;
string str = "";
int value = 12;
if (Enum.IsDefined(typeof (DocumentTypes),value))
str = ((DocumentTypes) value).ToString();
else
str = "Invalid Value";
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
DocumentTypes dt = DocumentTypes.Invalid; // Create an invalid enum
if (Enum.IsDefined(typeof (DocumentTypes),value))
dt = (DocumentTypes) value;
And for the bonus point, here is how to add a custom string to an enum (copied from this SO answer)
Enum DocumentType
{
[Description("My Document Type 1")]
Type1 = 1,
etc...
}
Then add an extenstion method somewhere
public static string GetDescription<T>(this object enumerationValue) where T : struct
{
Type type = enumerationValue.GetType();
if (!type.IsEnum)
throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
//Tries to find a DescriptionAttribute for a potential friendly name
//for the enum
MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
if (memberInfo != null && memberInfo.Length > 0)
{
object[] attrs = memberInfo[0].GetCustomAttributes(typeof (DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
{
//Pull out the description value
return ( (DescriptionAttribute) attrs[0] ).Description;
}
}
//If we have no description attribute, just return the ToString of the enum
return enumerationValue.ToString();
}
Then you can use:
DocumentType dt = DocumentType.Type1;
string str = dt.GetDescription<DocumentType>();
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.
public static string GetDescription(this Enum value)
{
var type = value.GetType();
var memInfo = type.GetMember(value.ToString());
if (memInfo.Length > 0)
{
var attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs.Length > 0)
return ((DescriptionAttribute)attrs[0]).Description;
}
return value.ToString();
}
First of all cast to your enum type and call ToString():
string str = ((DocumentTypes)12).ToString();