Check inside method whether some optional argument was passed

Well, arguments are always passed. Default parameter values just ensure that the user doesn’t have to explicitly specify them when calling the function.

When the compiler sees a call like this:

ExampleMethod(1);

It silently converts it to:

ExampleMethod(1, "default string", 10);

So it’s not techically possible to determine if the argument was passed at run-time. The closest you could get is:

if (optionalstr == "default string")
   return;

But this would behave identically if the user called it explicitly like this:

ExampleMethod(1, "default string");

The alternative, if you really want to have different behavior depending on whether or not a parameter is provided, is to get rid of the default parameters and use overloads instead, like this:

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
}

Leave a Comment