3

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,
}

2 Answers 2

10

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.

2
1

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.

1
  • Thanks for restructure my code. I think about the performance. Then I need return as early as possible.
    – Nano HE
    Commented Dec 16, 2010 at 6:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.