8

Does anybody know how to dynamically create a Func<T> instance?

//Create the Func type

Type funcType = typeof(Func<>).MakeGenericType(typeof(string)); 

//How do I pass a reference to the anonymous method? 

Activator.CreateInstance(funcType, () => "test");

This does not compile:

Cannot convert lambda expression to type object[] because it is not a delegate type

Anyone?

GSerg
  • 76,472
  • 17
  • 159
  • 346
seesharper
  • 3,249
  • 1
  • 19
  • 23
  • 5
    Try to describe what you're trying to achieve rather than how you're trying to achieve it for better chance of an answer. – Jamiec Feb 03 '12 at 09:17
  • I agree with Jamiec, because usually the Expression namespace is better in this kind of scenarios than hard-core reflection. – SWeko Feb 03 '12 at 09:22
  • seesharper can you take a look at this light inject question please? http://stackoverflow.com/questions/18931955/lightinject-ioc-container-throws-stackoverflow-when-resolving-type – JK. Sep 21 '13 at 11:21

3 Answers3

3

You need to use Expression trees:

var func = Expression.Lambda(Expression.Constant("test")).Compile();
var result = func.DynamicInvoke();
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
1

I don't think you can. This blog goes some way to explaining the issue. I suggest you look for an alternative approach. Can you use expression trees instead?

Myles McDonnell
  • 12,943
  • 17
  • 66
  • 116
0

You need a object which can be converted into System.Object, for this you need to create a delegate like Func<String> first. So it makes no sence for me to create the Func<T> at runtime.

Felix K.
  • 6,201
  • 2
  • 38
  • 71