3

I need your help.

Is it possible to do the following using c#?

I have a method

void SomeMethod(int p1 = 0, bool p2 = true, string p3 = "")
{
    // some code
}

And I need to call this method with unknown number of arguments on compile time. I mean on runtime the app should load info about arguments from xml (for example) and call the method with those arguments. Xml file may contains 0 to 3 arguments.

How to call the SomeMethod method with unknown number of arguments loaded from xml?

Thank you

4
  • Is 3 the max amount of args or is there possibly more as you can use the same name in function names with different args.
    – ZoomVirus
    Sep 25, 2014 at 14:34
  • Karl, no, 3 args are for example. It could be 10 or even 20.
    – Alex Maroz
    Sep 25, 2014 at 14:39
  • Why not just have List<Int>, List<String>, List<Boolean> ... ?
    – paparazzo
    Sep 25, 2014 at 14:45
  • Because of each argument has unique role in method. This is not just list of ids or list of names of something.
    – Alex Maroz
    Sep 25, 2014 at 14:48

2 Answers 2

6

You can do it using reflection:

  • Obtain MethodInfo passing all three parameter types.
  • Obtain run-time parameter values
  • Obtain parameter metadata ParameterInfo\[\] from MethodInfo by calling GetParameters()
  • For each missing parameter, check HasDefaultValue, and grab DefaultValue if it does
  • Append an array of default values to the array of values passed in. You will have an array of three objects
  • Pass the resultant array to the method that you obtained using reflection.
2
0

Read in the arguments into the variables and depending on how many were found, call SomeMethod. For example if you have valid values for p1, call SomeMethod(p1); valid values for p1 and p2, SomeMethod(p1, p2)...so on and so forth.

2
  • This is not gonna work. Because in case of 10 arguments I'll need to "hardcode" a lot of combinations.
    – Alex Maroz
    Sep 25, 2014 at 14:41
  • oh ok. That is what I was wondering if you had variable number of arguments. I think then what @dasblinkenlight proposes will. Sep 25, 2014 at 15:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.