简体   繁体   中英

Passing default parameter value (whatever it is)

//method with an optional parameter
public void DoSomething(int a, int b = 42);

//caller
DoSomething(a, b: default);

Can this be done in C#?

You might say, "if you don't want to set the parameter, just call the method without it". But then I get ugly IFs like this in my code:

//kinda ugly :(
if(parameterIsSet)
    DoSomething(a, myValue);
else
    DoSomething(a);

When I could do this instead:

DoSomething(a, b: parameterIsSet ? myValue : default);

I can of course do this:

DoSomething(a, b: parameterIsSet ? myValue : 42);

But I don't want to hardcode "42" in two places

In a case like this, I would usually use null as mentionned in a comment. Thus the code would look like this:

public void DoSomething(int a, int? bOverwrite = null)
{
    int b = bOverwrite ?? 42;
    // remaining code as before...
}

In such case, you would generally remove parameterIsSet variable and initialize a variable with null and set a value if necessary:

int? myB = null;
if (/* some condition */)
{
    myB = 29;
}

DoSomething(a, myB);

If you still have parameterIsSet , you could call the function like this:

DoSomething(a, parameterIsSet ? b : default(int?));

Other alternatives:

If you have many such parameters, it might be simpler to create a class for parameters and set its default in constructor:

class DoSomethingParameters
{
    public DoSomethingParameters() { A = 12; B = 42; }
    public int A { get; set; }
    public int B { get; set; }
}

var parameters = new DoSomethingParameters();
parameters.A = /* something */;

if (/* some condition */ {
    parameters.B = 29;
}

DoSomething(parameters);

And if some cases, the ugly IFs might be the best solution as many times, you might use the same condition to initialize b anyway or you need more variables to keep track of everything and the final code might be even uglier than the ugly code.

if (/* some condition */)
{
    int b = some_complet_expression;
    DoSomething(a, b);

    // Some other stuff here....
}
else
{
    DoSomething(a);

    // Different stuff here...
}

In particular, if you would have other code that depend on the condition after the call, it might be the base solution. Each case is specific. With experience, you learn how to write best code for the situation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM