How to dynamically call a method with optional arguments?
I need your help.
Can the following be done with 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 an unknown number of arguments at compile time. I mean, on startup, the application has to load the argument information from the xml (for example) and call a method with those arguments. The Xml file can contain 0 to 3 arguments.
How to call SomeMethod method with unknown number of arguments loaded from xml?
thank
+3
Alex maroz
source
to share
2 answers
You can do this using reflection:
- Receive
MethodInfo
passing of all three types of parameters. - Get runtime parameter values
- Get parameter metadata
ParameterInfo\[\]
fromMethodInfo
by callingGetParameters()
- For each missing parameter, check
HasDefaultValue
and takeDefaultValue
if it is - Add an array of default values to the array of passed values. You will have an array of three objects
- Pass the resulting array to the method you got with reflection.
+6
dasblinkenlight
source
to share
Read the arguments in 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, etc.
0
Aditya patil
source
to share