Well, arguments are always passed on. The default parameter values ββsimply ensure that the user does not need to explicitly specify them when calling the function.
When the compiler sees a call like this:
ExampleMethod(1);
He quietly converts it to:
ExampleMethod(1, "default string", 10);
Therefore, it is technically impossible to determine whether an argument was passed at run time. The closest you can get is:
if (optionalstr == "default string") return;
But this will behave the same if the user so explicitly calls it:
ExampleMethod(1, "default string");
An alternative, if you really want to have a different behavior depending on whether a parameter is provided, is to get rid of the default parameters and use overloads, for example:
public void ExampleMethod(int required) { // optionalstr and optionalint not provided } public void ExampleMethod(int required, string optionalstr) { // optionalint not provided } public void ExampleMethod(int required, string optionalstr, int optionalint) { // all parameters provided }
pswg
source share