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.