DataView Enumerator

  • Thread starter Thread starter Jack Jackson
  • Start date Start date
J

Jack Jackson

I am a little confused by DataView.

The Item property returns a DataRowView.

However, the object returned by the enumerator used by For Each is
apparently Object since I can specify any kind of object and don't get
a compiler error:

Dim dv as DataView
For Each xx As Integer In dv

Is the declared type of the item returned by the enumerator used by
For Each documented anywhere?

Why is it not declared as DataRowView?
 
Jack said:
I am a little confused by DataView.

The Item property returns a DataRowView.

However, the object returned by the enumerator used by For Each is
apparently Object since I can specify any kind of object and don't get
a compiler error:

Dim dv as DataView
For Each xx As Integer In dv

Is the declared type of the item returned by the enumerator used by
For Each documented anywhere?

Why is it not declared as DataRowView?

DataView only implements the non-generic IEnumerable interface, which
returns Object. For Each allows you to declare the iterating variable as any
type and will silently insert casts (which may fail at runtime). Prior to
..NET 2.0 (which introduced generics) this was the only way to do
enumeration. .NET 2.0 introduced IEnumerable(Of T) which allows for strongly
typed enumerations, but DataView dates from before this.

The items in DataView really are DataRowView objects, the interface just
doesn't express that.
 
DataView only implements the non-generic IEnumerable interface, which
returns Object. For Each allows you to declare the iterating variable as any
type and will silently insert casts (which may fail at runtime). Prior to
.NET 2.0 (which introduced generics) this was the only way to do
enumeration. .NET 2.0 introduced IEnumerable(Of T) which allows for strongly
typed enumerations, but DataView dates from before this.

The items in DataView really are DataRowView objects, the interface just
doesn't express that.

Thanks for the explanation. This makes me think that it is best to
not use a construct like For Each for non-generic classes in order to
get better compile time error checking.
 
Jack said:
This makes me think that it is best to not use a construct like For Each
for non-generic classes in order to get better compile time error
checking.

I'd dispute this, because the readability benefits of For Each offset the
type safety issues. It is true that you should always prefer generic
collections to non-generic collections where you have the choice, but where
you don't have the choice, I wouldn't abandon For Each on the off chance
that you make an error in determining the type of the collection. This is
not a particularly common error.
 
Back
Top