Archive Browser
Download CustomTypeConverter3.zip version 1.0.0.0, last updated 28/07/2013 (14.36 KB)
Download- md5: 12dfe9b74b052e3c18cd0c878b92b8f9
using System;
using System.ComponentModel;
using System.Reflection;
/*
Custom Type Converter Sample 3
http://cyotek.com/blog/using-alternate-descriptions-for-enumeration-members
*/
namespace CustomTypeConverter3
{
internal static class EnumExtensions
{
#region Class Members
public static string GetDescription<T>(this T value) where T : struct
{
FieldInfo field;
DescriptionAttribute attribute;
string result;
field = value.GetType().GetField(value.ToString());
attribute = (DescriptionAttribute)Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute));
result = attribute != null ? attribute.Description : string.Empty;
return result;
}
public static T GetValue<T>(string value, T defaultValue)
{
T result;
result = defaultValue;
foreach (T id in Enum.GetValues(typeof(T)))
{
FieldInfo field;
DescriptionAttribute attribute;
field = id.GetType().GetField(id.ToString());
attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attribute != null && attribute.Description == value)
{
result = id;
break;
}
}
return result;
}
#endregion
}
}
Donate
This software may be used free of charge, but as with all free software there are costs involved to develop and maintain.
If this site or its services have saved you time, please consider a donation to help with running costs and timely updates.
Donate