Johan
Johan

Reputation: 35194

Invoke method with optional arguments

I'm trying to invoke a method based on it's name with some optional arguments:

var methodInfo = this.GetType().GetMethod("Foo", 
                                BindingFlags.NonPublic | BindingFlags.Instance);

var queryString = _httpContext.Request.QueryString;
var somethingElse = new List<int>(){ 1,2,3 };
var args = new object[]{ queryString, somethingElse  };

if(methodInfo != null)
    methodInfo.Invoke(this, args);


private void Foo(object[] args)
{
    foreach(var item in args)
       //...
}

If I only pass the queryString to args I get the following error:

Object of type 'System.Web.HttpValueCollection' cannot be converted to type 'System.Object[]'.

How is the object[] parameters arguments in methodInfo.Invoke() intented to be used?

Upvotes: 0

Views: 996

Answers (2)

Knaģis
Knaģis

Reputation: 21485

Since your method takes a single parameter of type object[] you need to pass that parameter as an array inside another array.

// this is what is passed to your method as the first parameter
var args = new object[]{ queryString, somethingElse  };

// the .Invoke method expects an array of parameters...
methodInfo.Invoke(this, new object[] { args });

If your method would be void Foo(string a, List<int> b) etc. then the Invoke would be called like

// the .Invoke method expects an array of parameters...
methodInfo.Invoke(this, new object[] { queryString, somethingElse });

Upvotes: 1

Alessandro D&#39;Andria
Alessandro D&#39;Andria

Reputation: 8868

Try with:

methodInfo.Invoke(this, new object[] { args });

The parameter is only 1 and is an array of object. If you pass args it consider multiple parameters.

Upvotes: 4

Related Questions