You can (in theory) use a
return
at any point in your code, but there are those who will complain that you should have one exit, and one only. Me, I disagree - error exits are fine by me, as are "obvious" exits - where it would mess up the flow too much to make a "normal" exit worthwhile.
So it is perfectly legal to do this:
private MyClass MyMethod(List<MyClass> list)
{
foreach (MyClass mc in list)
{
if (mc.UserName == "Exit")
{
return mc;
}
}
return null;
}
Or this:
private MyClass MyMethod(List<MyClass> list)
{
for (int i = 0; i < list.Count; i++ )
{
if (list[i].UserName == "Exit")
{
return list[i];
}
}
return null;
}
But I would go with the former, as I have no need to know the index, or the number of items.