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.
fearofawhackplanet
source share