5

I've specified type in a variable: Type hiddenType. I need to create a Func<T> delegate where T is of type specified in mentioned variable and assign an method:

var funcType = typeof(Func<>).MakeGenericType(hiddenType); Func<object> funcImplementation = () => GetInstance(hiddenType); var myFunc= Delegate.CreateDelegate(funcType , valueGenerator.Method); 

It doesn't works - because funcImplementation is returns object instead of desired. At runtime, it will surely be an instance of type specified in hiddenType.

GetInstance returns object and signaure cannot be changed.

2
  • 1
    I do not see what you want to achieve. As GetInstance returns only object as per declaration the Func<object> is absolutly okay here. Commented Jun 18, 2015 at 13:17
  • 2
    @HimBromBeere OP wants myFunc to be Func<HiddenType>, not Func<object>. He tried using CreateDelegate for it, but it did not work. Commented Jun 18, 2015 at 13:22

2 Answers 2

5

You can solve this by building an expression tree manually, and inserting a cast to hiddenType. This is allowed when you construct an expression tree.

var typeConst = Expression.Constant(hiddenType); MethodInfo getInst = ... // <<== Use reflection here to get GetInstance info var callGetInst = Expression.Call(getInst, typeConst); var cast = Expression.Convert(callGetInst, hiddenType); var del = Expression.Lambda(cast).Compile(); 

Note: the above code assumes that GetInstance is static. If it is not static, change the way you construct callGetInst to pass the object on which the method is invoked.

Sign up to request clarification or add additional context in comments.

3 Comments

However the resulting delegate is not strongly typed which I assume the OP actually wanted.
@HimBromBeere This delegate will be strongly typed, in the sense that its type will be compatible with typeof(Func<>).MakeGenericType(hiddenType). Of course it would not be a statically typed delegate (which is not possible, because the type is hidden).
Thanks! I though for a while that Expression could do the thing, but I didn't know how to eat that piece of cake.
0

Instead of using a Type, you could consider using a generic wrapper, if it's not possible for you to change the GetInstance signature:

private Func<THidden> GetTypedInstance<THidden>() { return () => (THidden)GetInstance(typeof(THidden)); } 

Then you can just call it with

GetTypedInstance<SomeClass>(); 

instead of

GetInstance(typeof(SomeClass)); 

1 Comment

I think the problem is that hiddenType is only known at runtime thus statically binding to a generic wrapper won´t work.