The main difference between foreach
and using
is that foreach
is used for enumerating over an IEnumerable
whereas a using
is used for defining a scope outside of which an object will be disposed.
There is one similarity between foreach
and using
: Enumerators implement IDisposable
and a foreach
will implicitly wrap the use of an enumerator in a using
block. Another way of saying this is that is that a foreach
can be recoded as a using block and the resulting IL will be identical.
The code block
var list = new List<int>() {1, 2, 3, 4, 5};
foreach(var i in list) {
Console.WriteLine(i);
}
is effectively the same as
var list = new List<int>() {1, 2, 3, 4, 5};
using (var enumerator = list.GetEnumerator()) {
while (enumerator.MoveNext()) {
Console.WriteLine(enumerator.Current);
}
}