How can I create a Delegate with types only known at run time ?
I would like to do the following :
Type type1 = someObject.getType();
Type type2 = someOtherObject.getType();
var getter = (Func<type1, type2>)Delegate.CreateDelegate(
typeof(Func<,>).MakeGenericType(type1, type2), someMethodInfo);
How can I achieve something similar ?
I suspect you want
Expression.GetFuncType
as a simpler way of doing yourtypeof(...).MakeGenericType
operation.You can't have a compile-time type for
getter
that's more specific thanDelegate
though1, because you simply don't know that type at compile-time. You could potentially usedynamic
though, which would make it easier to invoke the delegate:1 As noted in comments, you could cast to
MulticastDelegate
, but it wouldn't actually buy you anything.You could create a generic method for that:
And I bet you can do something using the same philosophy with the Method to avoid all this reflection stuff.
Obs: that would work only if T1 and T2 are typed variables. If they are
as object
you'll get aFunc<object, object>
. But....if the objects you will give to the method areas object
as well, that would be no problem at all. And maybe you can even useFunc<object, object>
always, depending on your scenario.