Should I use early returns in C#?
- by Bobby
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;
}
}