"var" type inference in C# [duplicate]
Possible Duplicate:
Why does var evaluate to System.Object in “foreach (var row in table.Rows)”?
I was rather suprised to discovered 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"]);
}
Whats going on here?
Is this a type inference failure? And if so, what causes it?
Or is it part of the defined behaviour or var
? And if so, why?
I t开发者_运维技巧hought the idea of var
was that you could use it anywhere in a variable declaration/initialisation without changing behaviour.
The point here is not var, but the foreach loop. The foreach loop can optionally cast the iterator in addition to iterating 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();
}
So even if the list is of type object, it can be casted to int on the fly inside the foreach.
DataTable.Rows
returns System.Data.DataRowCollection
which is a subclass of InternalDataCollectionBase
.
The GetEnumerator
memthod on this returns IEnumerator
, rather than IEnumerator<DataRows>
.
Hence the only type information available is that it returns object
, so when you specify you are enumerating DataRow
you are adding your own cast, which var
does not.
The confusion is that foreach(SomeType thing in SomeCollection)
doesn't just iterate through the collection, it also attempts a cast to SomeType for each item as it iterates. But with var there's nothing to cast to.
精彩评论