views:

242

answers:

5

Hi, 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.

+1  A: 

It only gets called once and then stored.

SnOrfus
+9  A: 

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.

mquander
A: 

What you're doing is essentially the same thing. In the first situation, you're creating a reference to the DataRowCollection class, and then running the foreach, and in the first, you're not creating the reference. In both situations, you're calling .GetEnumerator() on the instance of the DataRowCollection that is on the heap.

You'll be calling it on the instance after the instance is retrieved from the method GetDataTable().

GetDataTable() is called only once.

David Morton
+2  A: 

Gustavo - to paraphrase an old CS professor of mine: the debugger is your friend! If you have a few minutes and some patience, you could wrap the extraction of the table in another class and place a breakpoint there. You'd find that, indeed, an object is created so that the call is not repeated.

Mark Brittingham
+2  A: 

A foreach loop is only syntaxic sugar for

var enumerator = MyMethod.GetDataTable().Rows.GetEnumerator();
while (enumerator.MoveNext())
{
    DataRow row = enumerator.Current;
    // Initial foreach content
}
Johann Blais
This is quite a good response, thank you!!
Gustavo Rubio