Junior
Junior

Reputation: 11990

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

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
}

Upvotes: 4

Views: 17017

Answers (2)

Iqon
Iqon

Reputation: 1992

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.

Upvotes: 8

igorc
igorc

Reputation: 2034

You can create yet another extention method for this.

public static object Create(this MyEnum enum)
{
    switch (enum)
    {
         case MyEnum.First:
              return new { IsFirst = true, UnitType = 1}];
         case MyEnum.Second:
              return new ...
         default:
              ...
    }
}

then use it like so:

dynamic first = MyEnum.First.Create();
var isFirst = first.IsFirst;

but you really should consider creating a factory to create your objects.

Upvotes: 0

Related Questions