DynamicFunc

CSharp · Console

/Program.cs

using System;
using System.Linq;
using System.Linq.Expressions;

					
public class Program
{
	public int TestMethod(bool arg)
	{
		Console.WriteLine("Called from compiled expression");
		return arg ? 0 : 1;
	}
	
	public static Func<object, object, object> CreateLambdaExpression(string tService, string methodName)
	{
		var inputServiceType = Type.GetType(tService);
		var methodInfo = inputServiceType.GetMethod(methodName);
		var inputType = methodInfo.GetParameters().First().ParameterType;

		var objType = typeof(object);
		var instance = Expression.Parameter(objType, "serviceInstance");
		var input = Expression.Parameter(objType, "inputData");
		var call = Expression.Call(
			Expression.Convert(instance, inputServiceType),
			methodInfo,
			Expression.Convert(input, inputType));
		var body = Expression.Convert(call, objType);

		var lambdaFunc = Expression.Lambda<Func<object, object, object>>(body, instance, input).Compile(); //<= this line throws the error.
		return lambdaFunc;
	}

	public static void Main()
	{
		var service = new Program();
		var func = CreateLambdaExpression(typeof(Program).FullName, "TestMethod");
        var result = func(service, true);
		Console.WriteLine(result);
	}
}
;