DataView Enumerator

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?
 
J

Jeroen Mostert

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.
 
J

Jack Jackson

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.
 
J

Jeroen Mostert

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top