Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create delegate with types known at runtime

Tags:

c#

.net

delegates

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 ?

like image 296
yhcowboy Avatar asked Aug 11 '26 12:08

yhcowboy


1 Answers

I suspect you want Expression.GetFuncType as a simpler way of doing your typeof(...).MakeGenericType operation.

var delegateType = Expression.GetFuncType(type1, type2);
Delegate getter = Delegate.CreateDelegate(delegateType, someMethodInfo);

You can't have a compile-time type for getter that's more specific than Delegate though1, because you simply don't know that type at compile-time. You could potentially use dynamic though, which would make it easier to invoke the delegate:

dynamic getter = ...;
var result = getter(input);

1 As noted in comments, you could cast to MulticastDelegate, but it wouldn't actually buy you anything.

like image 135
Jon Skeet Avatar answered Aug 13 '26 04:08

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!