Is it possible to add custom properties to c# enum object?

Junior picture Junior · Jul 14, 2017 · Viewed 8.3k times · Source

Using c# Is it possible using to associate properties for each enum items?

I have used the Description Attribute to add English description to an enum item.

To add English description to each item I have done the following

public enum MyEnum
{
    [Description("My First Item")]
    First,

    [Description("My Second Item")]
    Second,

    [Description("My Third Item")]
    Third
}

Then I added an extension method to my enum called GetDescription() which allows me to get the description like so

public static string GetDescription(this Enum value)
{
    Type type = value.GetType();

    string name = Enum.GetName(type, value);

    if (name != null)
    {
        FieldInfo field = type.GetField(name);
        if (field != null)
        {
            DescriptionAttribute attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (attr != null)
            {
                return attr.Description;
            }
        }
    }

    return name;
}

However, it will help me a lot if I am able to assign a class or construct a new object.

Is it possible/How can I do something like the follow?

public enum MyEnum
{
    [Description("My First Item"), new { IsFirst = true, UnitType = 1}]
    First
}

or using a class

public enum MyEnum
{
    [Description("My First Item"), new MyCustomClass(true, 1)]
    First
}

Answer

Iqon picture Iqon · Jul 14, 2017

You can decorate elements with custom Attributes. Those can contain nearly anything you want.

[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public class DescriptorAttribute : Attribute
{
    public bool IsFirst { get; }
    public int UnitType { get; }

    public DescriptorAttribute(bool isFirst, int unitType)
    {
        IsFirst = isFirst;
        UnitType = unitType;
    }
}

You would use this as follows:

public enum Test
{
    [Descriptor(isFirst: true, unitType: 2)]
    Element
}

you already have the code to read this attribute in your question.