Passing the 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 can say: "If you do not 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

+4
source share
1 answer

In that case, I would usually use nullas indicated in the comment. Thus, the code will look like this:

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

In this case, you usually delete the variable parameterIsSetand initialize the variable with zero and, if necessary, set the value:

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

DoSomething(a, myB);

parameterIsSet, :

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

:

, :

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);

IF , b , , , .

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

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

    // Different stuff here...
}

, , , . . , .

+4

Source: https://habr.com/ru/post/1660604/


All Articles