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

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Alex Maroz
  • 55
  • 4

2 Answers2

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.
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Good solution. I'll try to do it like this. Thanks. – Alex Maroz Sep 25 '14 at 14:42
  • +1... Readable and good to learn reflection, but correct one is to pass `Type.Missing` as arguments - http://stackoverflow.com/questions/2421994/invoking-methods-with-optional-parameters-through-reflection – Alexei Levenkov Sep 25 '14 at 14:44
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.

Aditya Patil
  • 548
  • 4
  • 14
  • This is not gonna work. Because in case of 10 arguments I'll need to "hardcode" a lot of combinations. – Alex Maroz Sep 25 '14 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. – Aditya Patil Sep 25 '14 at 15:12