Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Extending Enums with Custom Attributes

4.38/5 (10 votes)
7 Mar 2011CPOL 48.7K  
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:

C#
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:
C#
string txt = ExtensionTest.Get(typeof(EnumTest), "Left");
string txt = ExtensionTest.Get(EnumTest.Left)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)