Check inside method whether some optional argument was passed
How do I check if an optional argument was passed to a method?
public void ExampleMethod(int required, string optionalstr = "default string",
int optionalint = 10)
{
if (optionalint was passed)
return;
}
Another approach is to use Nullable<T>.HasValue
(MSDN definitions, MSDN examples):
int default_optionalint = 0;
public void ExampleMethod(int required, int? optionalint,
string optionalstr = "default string")
{
int _optionalint = optionalint ?? default_optionalint;
}
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
}
You can't, basically. The IL generated for these calls is exactly the same:
ExampleMethod(10);
ExampleMethod(10, "default string");
ExampleMethod(10, "default string", 10);
The defaulting is performed at the call site, by the compiler.
If you really want both of those calls to be valid but distinguishable, you can just use overloading:
// optionalint removed for simplicity - you'd need four overloads rather than two
public void ExampleMethod(int required)
{
ExampleMethodImpl(required, "default string", false);
}
public void ExampleMethod(int required, string optionalstr)
{
ExampleMethodImpl(required, optionalstr, true);
}
private void ExampleMethodImpl(int required, int optionalstr, bool optionalPassed)
{
// Now optionalPassed will be true when it's been passed by the caller,
// and false when we went via the "int-only" overload
}