Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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 thought the idea of var was that you could use it anywhere in a variable declaration/initialisation without changing behaviour.

like image 758
fearofawhackplanet Avatar asked Feb 08 '11 13:02

fearofawhackplanet


1 Answers

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.

like image 189
Øyvind Bråthen Avatar answered Oct 06 '22 00:10

Øyvind Bråthen