This code works:
foreach(DataColumn column in table.Columns)
{
// do whatever
}
But this code doesn’t:
(IEnumerable<DataColumn>)(table.Columns)
The .Columns property returns a DataColumnCollection which is an InternalDataCollectionBase, which implements IEnumerable, so it should work.
The error I get is
Cannot convert type ‘System.Data.DataColumnCollection’ to ‘System.Collections.Generic.IEnumerable’
DataColumnCollectionimplementsIEnumerable, and each returned row is aDataColumn, but it doesn’t implementIEnumerable<DataColumn>. As it doesn’t implement the interface, you can’t cast to the interface. As the class is sealed, the compiler knows that the value can’t possibly implement the interface, so you can’t even cast to it at compile-time.Use the LINQ
Castmethod insted:That’s effectively an adapter method – each element in the column collection will be lazily cast to
DataColumnas you fetch it from the result.The reason the
foreachcompiles is that the compiler adds an explicit cast for you. For instance, this will compile:… but it’ll throw an exception at execution time.