How do I check if an optional argument was passed to a method?
public void ExampleMethod(int required, string optionalstr = \"default string\",
int optio
Necromancing an old thread, but thought I'd add something.
default(int) or new int()For certain cases the default values can be used to check where an argument was passed. This works for multiple datatypes. https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/default-values-table
public void ExampleMethod(int optionalInt = default(int))
{
if (optionalInt == default(int)) //no parameter passed
//do something
else //parameter was passed
return;
}
This works particularly well when passing database ids where records hold unsigned integers greater than 0. So you know 0 will always be null and no ids can be negative. In other words, everything other than default(datatype) will be accepted as a passed parameter.
I would personally go with overloading methods, but another approach (which is perhaps outside the scope of this question) is to make the input parameters into a model. Then use the model force boundaries (like 10 being default parameter), which lets the model deal with the parameter, instead of the method.
public class Example
{
//...other properties
private int _optionalInt;
public int OptionalInt {
get => _optionalInt;
set {
if (value <= default(int))
throw new ArgumentOutOfRangeException("Value cannot be 0 or less");
else if (value == 10)
throw new ArgumentOutOfRangeException("Value cannot be 10");
else
_initValue = value;
}
}
public Example(int optionalInt)
{
OptionalInt = optionalInt; //validation check in constructor
}
}
This forces behavior before it reaches your method.
Hope this helps someone.