If I write a for, do, or while loop, is it possible to come out of this with the return keyword?
Eg:
class BreakTest
{
public static void Main()
{
You certainly can do what you're asking. There seem to be 2 camps on whether or not you should. There are some who say that there should only be 1 exit point from a function. They suggest that you should use a flag variable to record that you need to exit (and possibly any data that you need to return), and then return once you've broken out of your loop or reached the end of your if/else trees.
Personally, I have no problem with multiple exit points from a function, as long as they are symmetric. What do I mean by "symmetric"? Well, if I am going to return from inside of a loop, then I also want to return at the end of the loop (in case I never reach the condition in the loop that would cause me to return early). If I'm inside of a complex if/else heirarchy and I return from within one of the cases, then I should return from within all of them.
Here are some quick examples of how I prefer to write my code:
public string Search(IEnumerable<string> values)
{
foreach(string value in values)
{
if(SomeArbitraryCondition())
return value;
}
return null;
}
public int PerformAction()
{
if (SomeArbitraryCondition())
{
if (SomeArbitraryCondition())
{
return 1;
}
else
{
return 2;
}
}
else
{
if (SomeArbitraryCondition())
{
return 3;
}
else
{
return 4;
}
}
}
This isn't really a hard and fast rule that I've thought much about, but it's simply the way that I prefer to write it because it seems cleanest to me. In some cases, it makes more sense to use a flag variable and just return in one place.
public string Search(IEnumerable<string> values)
{
string found = null;
foreach(string value in values)
{
if(SomeArbitraryCondition())
found = value;
}
return found;
}
public int PerformAction()
{
int state;
if (SomeArbitraryCondition())
{
if (SomeArbitraryCondition())
{
state = 1;
}
else
{
state = 2;
}
}
else
{
if (SomeArbitraryCondition())
{
state = 3;
}
else
{
state = 4;
}
}
return state;
}
You can do this. Calling return;
will exit Main(). Normally you'd use break;
to break out of the for loop instead.
That being said, it's often considered bad practice to have multiple return locations within a single function. Many developers prefer to have a single return statement (if the method isn't declared with void
). This can make the code more easy to follow, from an understandability point of view, and hence easier to maintain and test.
Answer way overdue but return;
will exit your whole method (so out of your loop, too) if its return type is void. If it's not, it just won't compile unless your return the method's type.
Keep these in mind:
return
will exit the current method (Main in your example). Use break
to exit the loop.