18
foreach (var row in table.Rows)
{
     DoSomethingWith(row);
}

Assuming that I'm working with a standard System.Data.DataTable (which has a collection of System.Data.DataRow objects), the variable 'row' above resolves as an object type, not a System.Data.DataRow.

foreach (DataRow row in table.Rows)
{
     DoSomethingWith(row);
}

Works as I would expect. Is there a particular reason for this?

Thanks.

christofr
  • 2,680
  • 1
  • 18
  • 19
  • 2
    Duplicate of [Why can't I do foreach (var Item in DataTable.Rows)?](http://stackoverflow.com/questions/2325777/why-cant-i-do-foreach-var-item-in-datatable-rows) or [Why does var evaluate to System.Object in “foreach (var row in table.Rows)”?](http://stackoverflow.com/questions/2786727/why-does-var-evaluate-to-system-object-in-foreach-var-row-in-table-rows?lq=1). – Tim Schmelter Sep 27 '12 at 13:22

4 Answers4

22

That's because Rows is DataRowCollection, which in turn is IEnumerable and not IEnumerable<DataRow>, which means that type inferred will be object.

When you explicitly state type in foreach, you instruct c# to add cast to each call, which is why it works.

Sergei Rogovtcev
  • 5,804
  • 2
  • 22
  • 35
5

An implicit cast happens. Also note that an InvalidCastException can be thrown if the cast isn't possible.

PPC-Coder
  • 3,522
  • 2
  • 21
  • 30
4

table.Rows is a DataRowCollection which is IEnumberable ( and not IEnumerable<T>, T being DataRow), so it is not strongly typed to a DataRow, but a object i.e it is a collection of objects.

There is a DataTable extensions which you can use though - http://msdn.microsoft.com/en-us/library/system.data.datatableextensions.asenumerable.aspx

foreach (var row in table.AsEnumerable())
{

}
manojlds
  • 290,304
  • 63
  • 469
  • 417
1

Try this:

System.Data.DataTable dt = new System.Data.DataTable();

foreach (var row in dt.Rows.Cast<System.Data.DataRow>())
{

}

To use Rows.Cast you have to use System.Linq.

Jay Jose
  • 31
  • 4