Using var
as the iterator variable for a foreach block is more type safe than explicit type names. For example
class Item {
public string Name;
}
foreach ( Item x in col ) {
Console.WriteLine(x.Name);
}
This code could compile without warnings and still cause a runtime casting error. This is because the foreach loop works with both IEnumerable
and IEnumerable<T>
. The former returns values typed as object
and the C# compiler just does the casting to Item
under the hood for you. Hence it's unsafe and can lead to runtime errors because an IEnumerable
can contain objects of any type.
On the other hand the following code will only do one of the following
- Not compile because
x
is typed to object
or another type which does not have a Name field / property
- Compile and be guaranteed to not have a runtime cast error while enumerating.
The type of 'x' will be object
in the case of IEnumerable
and T
in the case of IEnumerable<T>
. No casting is done by the compiler.
foreach ( var x in col ) {
Console.WriteLine(x.Name);
}