Should I use early returns in C#?

Posted by Bobby on Stack Overflow See other posts from Stack Overflow or by Bobby
Published on 2010-01-15T13:24:29Z Indexed on 2010/04/12 13:03 UTC
Read the original article Hit count: 223

Filed under:
|
|
|

I've learned Visual Basic and was always taught to keep the flow of the program without interruptions, like Goto, Exit and Return. Using nested ifs instead of one return statement seems very natural to me.

Now that I'm partly migrating towards C#, I wonder what the best practice is for C-like languages. I've been working on a C# project for some time, and of course discover more code of ExampleB and it's hurting my mind somehow. But what is the best practice for this, what is more often used and are there any reasons against one of the styles?

public void ExampleA()
{
    if (a != b)
    {
        if (a != c)
        {
            bool foundIt;
            for (int i = 0; i < d.Count && !foundIt; i++)
            {
                if (element == f)
                    foundIt = true;
            }
        }
    }
}

public void ExampleB()
{
    if (a == b)
        return;

    if (a == c)
        return;

    foreach (object element in d)
    {
        if (element == f)
            break;
    }
}

© Stack Overflow or respective owner

Related posts about c-like

Related posts about program-flow