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 thought 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With