How do I check if an optional argument was passed to a method?
public void ExampleMethod(int required, string optionalstr = \"default string\",
int optio
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 not check directly but you can check it by default value. for example:
public void ExampleMethod(int required, string optionalstr = "default string",
int optionalint = 10)
{
if (optionalint == 10)
return;
}
or
public void ExampleMethod(int required, string optionalstr = "default string",
int? optionalint)
{
if (required.HasValue==false)
return;
}
Approach 2:
Also you can use override methods:
public void ExampleMethod(int required, string optionalstr = "default string")
{
//When this method called, means optionalint was NOT passed
}
public void ExampleMethod(int required, string optionalstr = "default string",
int optionalint)
{
//When this method called, means optionalint was passed
}
To determine whether an argument has been passed to an optional parameter
https://msdn.microsoft.com/en-us/library/849zff9h(v=vs.100).aspx
You can't, so you need to find a different way to check for the "optional" parameter. You can pass in a null if the parameter isn't being used, and then check
if (optionalstr != null)
{
// do something
}
You can also overload the method, having one taking the optional parameters and one that doesn't take the optional parameters. Also, you can make it so that the method without the optional parameters passes in nulls to one of the overloaded methods.
public void ExampleMethod(int required)
{
ExampleMethod(required, null, 0);
}
public void ExampleMethod(int required, string optionalstr = "default string",
int optionalint = 10)
{
}