9

I try create delegate type using an Expression class, but when I try create delegate from instance of MethodInfo I've got an ArgumentException. I using .NET 4.0 Here code:

        var method = /*...*/;
        List<Type> tArgs = new List<Type> { method.ReturnType };
        var mparams = method.GetParameters();
        mparams.ToList().ForEach(p => tArgs.Add(p.ParameterType));
        var delDecltype = Expression.GetDelegateType(tArgs.ToArray());
        return Delegate.CreateDelegate(delDecltype, method);

P.S. Sorry for my bad english;)

Alex Sabaka
  • 429
  • 1
  • 5
  • 10
  • Is [this](http://stackoverflow.com/questions/2714989/delegate-createdelegate-and-generics-error-binding-to-target-method/2715050#2715050) the solution to your problem? – adrianbanks Aug 12 '11 at 23:47

1 Answers1

12

If you read the documentation for Expression.GetDelegateType(), you would see that the return type has to be the last argument.

That means this code should work:

var tArgs = new List<Type>();
foreach (var param in method.GetParameters())
    tArgs.Add(param.ParameterType);
tArgs.Add(method.ReturnType);
var delDecltype = Expression.GetDelegateType(tArgs.ToArray());
return Delegate.CreateDelegate(delDecltype, method);

This code works for static methods only though. If you want create a delegate from instance method, you need to provide the instance you want to call the method on. To do that, change the last line to:

return Delegate.CreateDelegate(delDecltype, instance, method);
svick
  • 236,525
  • 50
  • 385
  • 514
  • It's didn't help. Same exception: ArgumentException "Error when linking with the final method." – Alex Sabaka Aug 13 '11 at 05:41
  • See edit, you probably have instance method, which means you need to provide the instance. – svick Aug 13 '11 at 12:10
  • Is there any way how to create dynamically also an delegate with `params` keyword for the last parameter type? – mvorisek Mar 22 '19 at 18:02
  • @Mvorisek Not with `Expression.GetDelegateType`. I think you would need to use Reflection Emit to do that. – svick Mar 24 '19 at 00:12
  • @svick Isn't `params` just a syntax sugar though? I believe for `params object[]` you should only specify `object[]`. – Javid Jul 02 '22 at 22:07