Search code examples
c#reflectionenumsattributesreflection.emit

Use C# EnumBuilder to create Enum with Attribute


I have used the EnumBuilder in C# to create Enums based on tables in my database. However, as my framework is designed, the enums we have also contain an attribute which is usually the name associated with the ID in the database.

What I am trying to accomplish is to keep the enums that are related to DB tables up to date without having to manually update them, and not lose the functionality it currently has with the attributes (even though they are rarely used).

So, is it possible to build an enum that also contains an attribute?

i.e.

public enum Example
{
   [StringValue("Some Name 1")]
   SomeName1 = 1,       
   [StringValue("Some Name 2")]
   SomeName2 = 2,
}

Update

Using the SetCustomAttribute I was able to add the attribute by adding the following to the existing code that created the enum.

Type myType = typeof(StringValueAttribute);
ConstructorInfo ci = myType.GetConstructor(new Type[] { typeof(string) });
// Other code
FieldBuilder fb = eb.DefineLiteral(name, result.ExampleID);
var cab = new CustomAttributeBuilder(ci, new object[] { result.Name });
fb.SetCustomAttribute(cab);

Solution

  • I haven't used EnumBuilder myself, but its DefineLiteral method returns a FieldBuilder which in turn exposes SetCustomAttribute which I suspect you could use to define the attribute for the field.