I have a project that stores some data from SQL in a DataTable
and then maps each DataRow
to a custom class instance.
When I loop over the Rows
property (which is of type DataRowCollection
), there's no type inference.
So this doesn't work:
var dt = new DataTable();
foreach(var row in dt.Rows)
{
int id = Int32.Parse(row.ItemArray[0].ToString());
// doesn't compile
}
But this does:
var dt = new DataTable();
foreach(DataRow row in dt.Rows)
{
int id = Int32.Parse(row.ItemArray[0].ToString());
}
Why can't the compiler figure out of what type the row
is? Could the var
keyword stand for something else in the case of enumerating over a DataRowCollection
? Is there something else, besides data rows, that could be enumerated over in a DataRowCollection
?
Is that why you would need to be explicit?
Because DataRowCollection
implements IEnumerable
(via InternalDataCollectionBase
) but not the generic, typed IEnumerable<T>
. The class is simply too old.
By specifying the type in the foreach
you're casting it implicitely.