SpiritBob
SpiritBob

Reputation: 2652

How to invoke with reflection a method that accepts a Func<> parameter?

When I try to add the Func<> parameter in the array of MethodInfo.Invoke, it's giving me the error that it can't convert a method group to an object.

How do I deal with this?

The method's signature:

static bool Something(Func<Expression, Expression, BinaryExpression> body)

What I'm passing:

MethodInfo.Invoke(null, new object[] { Expression.Subtract }); // compilation error

CS0428 Cannot convert method group 'Subtract' to non-delegate type 'object'. Did you intend to invoke the method?

Upvotes: 1

Views: 731

Answers (1)

Sweeper
Sweeper

Reputation: 270768

There is indeed no conversion from method groups to object, but there are conversions from method groups to compatible delegate types (method group conversions), and there are also conversions from delegate types to object. So you can first convert the method group to Func<Expression, Expression, BinaryExpression> with a cast, then it can be implicitly converted to object:

someMethodInfo.Invoke(null, new object[] { (Func<Expression, Expression, BinaryExpression>)Expression.Subtract });

Upvotes: 2

Related Questions