How does foreach work when looping through function results?

Viewed 3997

Suppose I have the following code:

foreach(string str in someObj.GetMyStrings())
{
    // do some stuff
}

Will someObj.GetMyStrings() be called on every iteration of the loop? Would it be better to do the following instead:

List<string> myStrings = someObj.GetMyStrings();
foreach(string str in myStrings)
{
    // do some stuff
}

?

4 Answers

Just to round the question off in case you fall into a "all for's are the same";

for(int x=0;x < ProvideCeiling(); x++)

does call the function each time.

Related