Check inside method whether some optional argument was passed

Viewed 16720

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;
}
10 Answers

Necromancing an old thread, but thought I'd add something.

You can use 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.

Use nullable is a good solution.. see example below

public static void ExampleMethod(bool? optionalBool = null)
{
    Console.WriteLine(optionalBool == null ? "Value not passed" : "Value passed");
}


public static void Main()
{
    ExampleMethod();
    ExampleMethod(true);
    ExampleMethod(false);
}
Related