FOR-EACH over an IEnumerable vs a List

  • A+

Is there any benefit or difference if my for-each loop is going through the method argument if I pass in that argument as an IEnumerable or if I pass that argument as a List?


No there isn't. In both cases the for-each is translated to something like this

var enumerator = input.GetEnumerator(); while(enumerator.MoveNext()) {   // loop body } 

Additionally, if the enumerator is disposable, it will be disposed after the loop.

Jon Skeet gives a detailed description here.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: