Search code examples
c#dynamicpropertiescustom-attributestypebuilder

TypeBuilder - Adding attributes


I have a helper class that uses a TypeBuilder to construct a dynamic type. It is used as follows :

var tbh = new TypeBuilderHelper("MyType");
tbh.AddProperty<float>("Number", 0.0f);
tbh.AddProperty<string>("String", "defaultStringValue");
tbh.Close();

var i1 = tbh.CreateInstance();
var i2 = tbh.CreateInstance();

I now want to add support for property attributes (existing attribute types, not dynamically generated types), along the lines of :

public class TypeBuilderHelper
    {
        public void AddProperty<T>(string name, T defaultValue, params Attribute[] attributes)
        {
            // ...
        }
    }

public class SomeAttribute : Attribute
    {
        public SomeAttribute(float a) { }
        public SomeAttribute(float a, int b) { }
        public SomeAttribute(float a, double b, string c) { }
    }

 var tbh2 = new TypeBuilderHelper("MyType2");
 tbh2.AddProperty<float>("Number", 0.0f, new SomeAttribute(0.0f, 1));
 tbh2.AddProperty<string>("String", "defaultStringValue");
 tbh2.Close();

 var i3 = tbh.CreateInstance();
 var i4 = tbh.CreateInstance();

But I'm not sure how that would work. I'm creating the properties using the PropertyBuilder, but the CustomAttributeBuilder wants a constructor signature and the constructor args, where as all I'll have is an instance of a constructed Attribute.


Solution

  • An instance of an attribute isn't helpful here you need to define the constructor and the values that should be called. A simple solution might be to change the AddProperty Signature and exchange the params Attribute Parameter with a params CustomAttributeBuilder Parameter and construct Builder instances instead of attributes.

    var ci = typeof(SomeAttribute).GetConstructor(new Type[] { typeof(float), typeof(int) });
    var builder = new CustomAttributeBuilder(ci, new object[] { 0.0f, 1 });