Search code examples
c#.net-3.5expression-trees

Using Ast.Expressions to create a delegate


I'm experimenting with Expressions (Microsoft.Scripting.Ast) and need to assign a delegate variable with a delegate to another instance method and then call that delegate. Unfortunately I'm very clueless :(

var @delegate = Expression.Variable (typeof (Delegate));
var expression = Expression.Block(
     new [] { @delegate },
     Expression.Assign(@delegate, /* MISSED PART */),
     Expression.Call(@delegate, typeof(Delegate).GetMethod("DynamicInvoke"))
);

Please tell me if I missed anything. This is for my lately started internship. So it is possible that it makes no sense at all ^^


Solution

  • The answer was Expression.GetDelegateType(...)

    Here is a code snippet that creates a delegate for a MethodInfo:

    public static Type GetDelegateType (this MethodInfo methodInfo)
    {
      var parameterTypes = methodInfo.GetParameters ().Select (x => x.ParameterType);
      var returnType = new[] { methodInfo.ReturnType };
    
      var delegateTypes = parameterTypes.Concat (returnType).ToArray ();
      return Expression.GetDelegateType (delegateTypes);
    }