ListItemCollection.GetEnumerator returns the counter that was used with .NET 1.0, which returns the object as a value. The foreach pattern (as Eric Lippert explains in much more detail) requires the Enumerator object to be returned by the GetEnumerator method.
When you use var, the compiler introduces the type of the loop variable as an object, since Current of Enumerator returns only the object.
public interface IEnumerator { bool MoveNext(); object Current { get; } void Reset(); }
But when you use foreach(ListItem item in xxx) ..., the compiler automatically adds the cast to ListItem from the object for you. You can try when you do foreach (string str in the new object [] {"str", 1}), which will result in an InvalidCastException. There is no keyword var . It just concludes the type without too much magic.
When you expect a ListItem in your loop, you should write it clearly. It is not clear from the signature of the enumerator method which objects it will return. You must tell the compiler what types you expect. Another reason not to use the var keyword is because readers of your code will also not be able to infer the type of your loop variable.
source share