Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# better to initialize list then loop over it, or just initialize in loop condition?

I end up with a lot of code like this:

List<string> dates = someMethodCall();
foreach (string dateStr in dates) { }

I usually declare the object over which I'm iterating and then use it in the foreach condition out of worry that someMethodCall() would happen for each iteration of the loop. Is this the case? I would prefer to do this:

foreach (string dateStr in someMethodCall()) { }

But I only want to do that if someMethodCall() happens only once and then its results are cached for each subsequent iteration.

like image 415
Sarah Vessels Avatar asked Jan 25 '10 21:01

Sarah Vessels


2 Answers

The method will be called only once in both cases.

The first method has a readability advantage as you can name the variable and describe what's in it with its name. It will make the code more self-documenting and improves maintainability.


To quote the authoritative source on this:

C# Language Specification - 8.8.4 The foreach statement

 foreach (V v in x) embedded-statement

is then expanded to:

{
  E e = ((C)(x)).GetEnumerator();
  try {
  V v;
      while (e.MoveNext()) {
          v = (V)(T)e.Current;
          embedded-statement
      }
  }
  finally {
      … // Dispose e
  }
}

It's clear that the expression x in the above foreach statement is evaluated only once in the expansion.

like image 62
mmx Avatar answered Oct 19 '22 06:10

mmx


foreach will evaluate the collection once, get the iterator, and then use that for its iteration.

like image 38
Anon. Avatar answered Oct 19 '22 06:10

Anon.