Is it possible to add custom properties to c# enum object?
10,224
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.
Author by
Junior
Updated on July 25, 2022Comments
-
Junior almost 2 years
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
calledGetDescription()
which allows me to get the description like sopublic 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 }
-
Leandro almost 7 years
-
Pierre-Luc Pineault almost 7 yearsAt this point, shouldn't you just use polymorphism instead of using enums?
-
Jeremy Thompson almost 7 yearsEnum's are essentially integers and you want to store an int, string and class, use a
Tuple<int, string, object> tuple = new Tuple<int, string, object>(1, "First Item", new MyCustomClass(true, 1));
-
Junior almost 7 years@Pierre-LucPineault can you please show an example of how to do that?
-
Iqon almost 7 years@MikeA if one of the answers solved your problem, please mark it as resolved. If not please clarify what still is missing in the existing answers.
-