FAQ
overflow

Great Answers to
Questions About Everything

QUESTION

In the situation where I am looping through a collection looking for an item, is it better practice to break before I return or should I break then return?

Return during loop:

foreach(string item in items)
{
    string[] split = item.Split('|');
    if(split[0] == searchFor)
        return split[1];
}
return null;

or

Break then return:

string result = null;
foreach(string item in items)
{
    string[] split = item.Split('|');
    if(split[0] == searchFor)
    {
        result = split[1];
        break;
    }
}
return result;

{ asked by Benny }

ANSWER

If you break, you need to introduce an additional variable. In my opinion, it's more clear to return as soon as possible from any function.

{ answered by recursive }
Tweet