0
DataTable test = new DataTable();
foreach (var r in test.Rows)
{
    r[1].tostring();
}

Why doesn't the compiler understand that r is a DataRow? See the below image for the error message.

enter image description here

ViV
  • 1,998
  • 8
  • 27
  • 54

3 Answers3

12

The property DataTable.Rows uses an older style (non-generic) collection. The actual type is DataRowCollection which defines an enumerator that is non-generic so it returns instances of type object. To address this problem a new extension method was provided in later versions of the framework (3.5+) called DataTable.AsEnumerable that returns a properly-typed enumerator:

DataTable test = new DataTable();
foreach (var r in test.AsEnumerable())
{
    r[1].ToString();
}

If you are stuck on an older version of .NET you would have to cast r to DataRow manually.

mellamokb
  • 56,094
  • 12
  • 110
  • 136
1

The Type of DataTable.Rows is DataRowCollection which inherits from InternalDataCollectionBase, which inherits from ICollection, the non-generic one. So it is not an ICollection<DataRow>, but a collection of objects. See here.
With foreach (DataRow r in test.Rows), you are explicitly telling C# to cast each object to a DataRow

Dennis_E
  • 8,751
  • 23
  • 29
0

var is an implicit type ! It aliases any type! When you declare a "var type" you are basically telling the compiler hey look I don't know what type is appropriate for this so whatever type the expression on the right evaluates to that is the appropriate type!

So, Here obviously each row is returned as an object so unless you cast them to the appropriate type they will remain as an object!

Rahul Jha
  • 1,131
  • 1
  • 10
  • 25