Type "var" output in C #

Possible duplicate:
Why does var evaluate System.Object to "foreach (var row in table.Rows)"?

I was very surprised to learn the following today.

SqlDataReader reader = cmd.ExecuteReader(); DataTable schemaTable = reader.GetSchemaTable(); // the following compiles correctly foreach (DataRow field in schemaTable.Rows) { Console.WriteLine(field["ColumnName"]); } // the following does not compile as 'var' is of type 'object' foreach (var field in schemaTable.Rows) { // Error: Cannot apply indexing with [] to an expression of type 'object' Console.WriteLine(field["ColumnName"]); } 

What's going on here?

Is this a type inference error? And if so, what causes it?

Or is it part of a specific behavior or var ? And if so, why?

I thought the idea of var was that you can use it anywhere in the declaration / initialization of variables without changing the behavior.

+6
c # type-inference var
source share
3 answers

The point here is not var, but a foreach loop. The foreach loop can optionally cast an iterator in addition to the iteration itself.

So you can do the following:

 List<object> test = new List<object>(); test.Add(1); test.Add(2); test.Add(3); foreach( int i in test ){ i.Dump(); } 

Thus, even if the list has an object type, it can be launched in int on the fly inside the foreach.

+3
source share

DataTable.Rows returns System.Data.DataRowCollection , which is a subclass of InternalDataCollectionBase .

GetEnumerator memto on this returns an IEnumerator , not an IEnumerator<DataRows> .

Therefore, only type information is available, that it returns an object , so when you specify, you enumerate a DataRow , you add your own listing, which var does not have.

+1
source share

The confusion is that foreach(SomeType thing in SomeCollection) not only foreach(SomeType thing in SomeCollection) through the collection, but also tries to cast SomeType for each element as it iterates. But with var there is nothing to throw.

0
source share

All Articles