Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Activator.CreateInstance to create Func<T> instances

Tags:

c#

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?

like image 480
seesharper Avatar asked Feb 03 '12 09:02

seesharper


2 Answers

You need to use Expression trees:

var func = Expression.Lambda(Expression.Constant("test")).Compile();
var result = func.DynamicInvoke();
like image 178
Daniel Hilgarth Avatar answered Nov 09 '22 01:11

Daniel Hilgarth


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?

like image 1
Myles McDonnell Avatar answered Nov 09 '22 03:11

Myles McDonnell