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.
That's because
Rows
isDataRowCollection
, which in turn isIEnumerable
and notIEnumerable<DataRow>
, which means that type inferred will beobject
.When you explicitly state type in
foreach
, you instruct c# to add cast to each call, which is why it works.Try this:
To use Rows.Cast you have to use System.Linq.
table.Rows
is a DataRowCollection which isIEnumberable
( and notIEnumerable<T>
, T beingDataRow
), so it is not strongly typed to aDataRow
, 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.aspxAn implicit cast happens. Also note that an InvalidCastException can be thrown if the cast isn't possible.