General question with a question about returning to C #

How to return value if I don't need hit2 block.

Does this make sense or not? I think multi should not be used return, but I cannot replace it with break. there is no closed loop from which one can break or continue.

public EnResult MyFun()
{
    bool bRet = default;

    // block1 . higher priority than block2.
    if (true)
    {
    // if bRet = true_1, not need hit block2. That why I want to nested my code with multi *return*
        return bRet = true_1;  
    }
    else
    {
        // do nothing
    }

    // block2
    if (true)
    {
        return bRet = true_2;
    }
    else
    {
        // do nothing
    }

    return bRet;
}

public enum EnResult
{
    true_1,
    true_2,
    false_1,
    false_2,
    default,
}
+3
source share
2 answers

Using multiple return statements for each method is not a bad coding style at all. Limiting one return statement makes sense in C, where you might need gotosome general cleanup code that will contain free pointers, etc., and then return the value you saved in the variable. But in C #, this is not necessary.

. , , , , return .

+10

"multi-return":

public EnResult MyFun()
{
    // I changed 'default' to 'None' because I wasn't sure if it compiled
    EnResult result = EnResult.None;

    // block1 . higher priority than block2.
    if (true)
    {
        result = EnResult.true_1;
    }
    else
    {
        // do nothing
    }

    // block2
    if (result == EnResult.None)
    {
        if (true)
        {
            result = EnResult.true_2;
        }
        else
        {
            // do nothing
        }
    }

    return result;
}

public enum EnResult
{
    None,  
    true_1,
    true_2,
    false_1,
    false_2,

}

( ). , .

+1

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


All Articles