Nano HE
Nano HE

Reputation: 9307

General Multi Return Statement Question in C#

How to return the value if I doesn't need hit block2.

Does it make sense or not? I think I shouldn't use multi return, but I can't replace it with break. there is No enclosing loop out of which to 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's 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,
}

Upvotes: 3

Views: 1769

Answers (2)

Marlon
Marlon

Reputation: 20312

If you don't want to use a "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,

}

I would prefer using multiple return statements though (your original code). It's much more clear that way IMO.

Upvotes: 1

cdhowie
cdhowie

Reputation: 169403

Using multiple return statements per method is not poor coding style at all. Limiting yourself to one return statement makes sense in C, where you may need to goto some common cleanup code that will free pointers, etc., and then return the value you have stored in a variable. But in C# this is not necessary.

I write methods with multiple return statements all the time. I would much rather read a method written with multiple return statements where the logic flow is clear, than read a method written with one return statement and somewhat obfuscated logic.

Upvotes: 10

Related Questions