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