1

Does the current .NET compiler treat these differently?

List<string> stuff = GetSomeStuff();
foreach(string thing in stuff) { ... }

vs

foreach(string thing in GetSomeStuff()) { ... }
Lee
  • 3,869
  • 12
  • 45
  • 65
  • Possible duplicate of [How does foreach work when looping through function results?](https://stackoverflow.com/questions/1632810/how-does-foreach-work-when-looping-through-function-results) – Alex K. Aug 06 '17 at 10:41
  • The only benefit of the former is if you want to do something **else** with the `stuff` variable. For your code as is, you may as well use the latter. – mjwills Aug 06 '17 at 11:49

1 Answers1

1

If you enable compiler optimisations then both sets of code will compile to identical IL. For example, this is the IL output for the main method when using LinqPad:

IL_0000:  ldarg.0     
IL_0001:  call        UserQuery.GetSomeStuff
IL_0006:  callvirt    System.Collections.Generic.List<System.String>.GetEnumerator
IL_000B:  stloc.0     
IL_000C:  br.s        IL_0016
IL_000E:  ldloca.s    00 
IL_0010:  call        System.Collections.Generic.List<System.String>.get_Current
IL_0015:  pop         
IL_0016:  ldloca.s    00 
IL_0018:  call        System.Collections.Generic.List<System.String>.MoveNext
IL_001D:  brtrue.s    IL_000E
IL_001F:  leave.s     IL_002F
IL_0021:  ldloca.s    00 
IL_0023:  constrained. System.Collections.Generic.List<>.Enumerator
IL_0029:  callvirt    System.IDisposable.Dispose
IL_002E:  endfinally  
IL_002F:  ret  
DavidG
  • 113,891
  • 12
  • 217
  • 223