Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a method that returns a collection get called in every iteration in a foreach statement in C#?

I was working with some C# code today in the morning and I had something like:

foreach(DataRow row in MyMethod.GetDataTable().Rows) {
//do something
}

So, as I dont have a full understanding of the language framework I would like to know if GetDataTable() gets called each time an iteration is done or if it just gets called once and the resulting data (which would be Rows) is saved in memory to loop through it. In any case, I declared a new collection to save it and work from there...

I added a new variable so instead I did:

DataRowCollection rowCollection = MyMethod.GetDataTable().Rows;
foreach(DataRow row in rowCollection) {
//do something
}

But im not quite sure if this is necessary.

Thanks in advance.

like image 550
Gustavo Rubio Avatar asked Jan 28 '09 18:01

Gustavo Rubio


People also ask

What can foreach statements iterate through?

The foreach loop in C# iterates items in a collection, like an array or a list. It proves useful for traversing through each element in the collection and displaying them. The foreach loop is an easier and more readable alternative to for loop.

What does the foreach statement do?

The foreach statement: enumerates the elements of a collection and executes its body for each element of the collection. The do statement: conditionally executes its body one or more times.

Does foreach call Dispose?

Yes, foreach will call Dispose() on the enumerator if it implements IDisposable.

Which method is used to iterate through the items in the collection?

An iterator method or get accessor performs a custom iteration over a collection. An iterator method uses the yield return statement to return each element one at a time.


2 Answers

Don't worry about it; it'll only execute GetDataTable() once internally to get the enumerator object from the DataRowCollection, and then fetch a new item from it every run through the loop.

like image 66
mqp Avatar answered Oct 01 '22 07:10

mqp


A foreach loop is only syntaxic sugar for

var enumerator = MyMethod.GetDataTable().Rows.GetEnumerator();
while (enumerator.MoveNext())
{
    DataRow row = enumerator.Current;
    // Initial foreach content
}
like image 40
Johann Blais Avatar answered Oct 01 '22 09:10

Johann Blais