Delegate in C# attribute

I am looking to put a static delegate inside of a custom attribute. What I am running into is Activator.CreateInstance is a major bottle neck and I'd like to avoid it. I am using Mono and running on iOS so compiled lambda and any JIT'd method is out of question. What I was hoping to do is put a static factory constructor on each class that has the attribute. So it would be something like:

[CustomAtt("cool",FactoryMethod)]
public class SomeClass{
    public static SomeClass FactoryMethod(){
        return new SomeClass()
    }
}

This gives me a compile error An Attribute must be a constant expression, typeof expression or array creation expression

The reason I was going to stick it in the attribute is all of the objects I will be creating already have the attribute and I have the attribute when I need to create the object.

Is there another way to accomplish this, or another faster way of creating objects.

Jon Skeet
people
quotationmark

Sounds like you want Delegate.CreateDelegate. Specify the method name and the type, find the method with reflection (once) and then create a delegate from it. You could potentially do that within the attribute constructor, although I typically do very little in attribute types themselves. Another alternative would be to make whatever's consuming the attribute do the work and cache the delegate.

Although this requires reflection and the ability to create a delegate on the fly, I would expect both of those to be supported within Mono on iOS (by which I assume you mean Xamarin.iOS, unless you're rolling your own solution).

people

See more on this question at Stackoverflow