Alex Sabaka
Alex Sabaka

Reputation: 429

Create delegate type in runtime

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;)

Upvotes: 9

Views: 8315

Answers (1)

svick
svick

Reputation: 244767

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);

Upvotes: 13

Related Questions