Extending Enums with Custom Attributes






4.38/5 (8 votes)
Extending Enums with Custom Attributes
Sometimes we are too lazy to create a class. Enumerations are very simple to create and use but they haven't any properties or fields. So, we can only add custom attributes (I used strings, but it's possible to use more complex types). I think the simplest way to do it is as follows:
using System;
using System.Reflection;
namespace Test
{
[AttributeUsage(AttributeTargets.Field)]
public class ExtensionTest : Attribute
{
private string m_name;
public ExtensionTest(string name)
{
this.m_name = name;
}
public static string Get(Type tp, string name)
{
MemberInfo[] mi = tp.GetMember(name);
if (mi != null && mi.Length > 0)
{
ExtensionTest attr = Attribute.GetCustomAttribute(mi[0],
typeof(ExtensionTest)) as ExtensionTest;
if (attr != null)
{
return attr.m_name;
}
}
return null;
}
public static string Get(object enm)
{
if (enm != null)
{
MemberInfo[] mi = enm.GetType().GetMember(enm.ToString());
if (mi != null && mi.Length > 0)
{
ExtensionTest attr = Attribute.GetCustomAttribute(mi[0],
typeof(ExtensionTest)) as ExtensionTest;
if (attr != null)
{
return attr.m_name;
}
}
}
return null;
}
}
public enum EnumTest
{
None,
[ExtensionTest("(")] Left,
[ExtensionTest(")")] Right,
}
}
Usage:
string txt = ExtensionTest.Get(typeof(EnumTest), "Left");
string txt = ExtensionTest.Get(EnumTest.Left)