Ergwun
Ergwun

Reputation: 12978

Create delegate for property acessor obtained via reflection when property type unknown

In .NET 2.0 (with C# 3.0), how can I create a delegate for a property accessor obtained via reflection when I don't know its type at compile time?

E.g. if I have property of type int, I can do this:

Func<int> getter = (Func<int>)Delegate.CreateDelegate(
    typeof(Func<int>),
    this, property.GetGetMethod(true));
Action<int> setter = (Action<int>)Delegate.CreateDelegate(
    typeof(Action<int>),
    this, property.GetSetMethod(true));

but if I do not know what type the property is at compile time, I don't know how to do it.

Upvotes: 5

Views: 2679

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063944

What you need is:

Delegate getter = Delegate.CreateDelegate(
    typeof(Func<>).MakeGenericType(property.PropertyType), this,
    property.GetGetMethod(true));
Delegate setter = Delegate.CreateDelegate(
    typeof(Action<>).MakeGenericType(property.PropertyType), this,
    property.GetSetMethod(true));

however, if you are doing this for performance, you are still going to come up short, since you would need to use DynamicInvoke(), which is slooow. You might want to look at meta-programming to write a wrapper that takes/returns object. Or look at HyperDescriptor which does this for you.

Upvotes: 3

Related Questions