2

I would like to Invoke this method:

public IEnumerable<TEntity> SelectAll(params string[] entitiesToLoad)

But at the most of times I will not load relational entities, so I'd like to invoke it without send entitiesToLoad values, like this:

var dbResult = methodInfo.Invoke(repository, null);

But it throws an exception, because the number of parameter is not equivalent.

Is there a way to perform this without change the params string[] to another type of parameter?

I tried string entitiesToLoad = null as parameter, I got the same error.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Raphael Ribeiro
  • 529
  • 5
  • 18

2 Answers2

6

Pass an empty array, because that is what the C# compiler will pass when indicating no arguments for a variadic method:

var dbResult = methodInfo.Invoke(repository, new object[] { new string[0] });

Note that you will have to wrap the string array into an object array, because that object array represents the list of arguments. The first passed argument is then the empty string array.

O. R. Mapper
  • 20,083
  • 9
  • 69
  • 114
2

It seems that this is a perfect scenario to use overload of methods. If you don´t need the value, why to send it?:

public IEnumerable<TEntity> SelectAll(params string[] entitiesToLoad)
{
     //...
}

public IEnumerable<TEntity> SelectAll()
{
     //...
}
NicoRiff
  • 4,803
  • 3
  • 25
  • 54
  • I would like to use as optional – Raphael Ribeiro Jan 10 '17 at 12:30
  • It would be much cleaner that if you don´t need it you just don´t send it. But if you insist on doing that, You can just set as optional and it should work as i´ve tested it public IEnumerable SelectAll(string[] entitiesToLoad = null) – NicoRiff Jan 10 '17 at 12:37
  • Can you show the line that you invoke the method, I got the same error here. – Raphael Ribeiro Jan 10 '17 at 12:50
  • that way you can call it like this: SelectAll(); – NicoRiff Jan 10 '17 at 12:56
  • 1
    Sorry but you didn't understand , I am invoking the method via Reflection, by using MethodInfo.Invoke. The way that you did works, but I'm in a generic scenario – Raphael Ribeiro Jan 10 '17 at 13:01
  • That is not supported by reflection. The only way to accomplish that is to send the value when calling the method. http://stackoverflow.com/a/2422015/637840 – NicoRiff Jan 10 '17 at 13:07
  • @NicoRiff: Of course it is supported by reflection - everything that you can call in code can be called via reflection, too. However, you will have to do the overload resolution yourself by looking at the argument lists. – O. R. Mapper Jan 10 '17 at 14:07