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;
}
Jon Skeet
people
quotationmark

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
}

people

See more on this question at Stackoverflow