Jacob Pressures
Jacob Pressures

Reputation: 1461

DirectCast One derived Collection into base Collection

I'm working with old VB 6.0 code that in now in VB.NET. So it is using some obsolete collection types. I'm trying to upgrade these as much as possible without breaking stuff.

Say I have a collection of Books HashSet(Of Book) and I have a collection of Premium Books HashSet(Of PremiumBook).

PremiumBook is derived from Book. The only difference is that I override the EQUALS and HASHCODE methods. Everything else is the same.

Since PremiumBook is a Book I can do:

Dim anyBook as Book
Dim goldBook as PremiumBook = New PremiumBook()
anyBook = goldBook

So why can't I do

DirectCast(HashSet(Of PremiumBook), HashSet(Of Book))

The error that I'm getting is: "Value of type System.Collections.Generic.HashSet(Of SameNamespace.Different.frmBookManager.PremiumBook)' cannot be converted to 'System.Collections.Generic.HashSet(Of SameNamespace.Something.Book)'.

Is it because the namespaces are different? That doesn't make any sense to me.

I feel as if i have a collection of objects, any derived type should be able to fit in that collection.

Thanks!

Upvotes: 2

Views: 71

Answers (1)

Kelly Barnard
Kelly Barnard

Reputation: 1141

You can not cast two different object type collections even if they are inherited, but you can cast the individual members to the inherited class Like This example:

Option Strict On
Option Explicit On

Module Module1

    Sub Main()

        Dim Booklist As List(Of Book) = New List(Of Book)

        Booklist.Add(New PremiumBook())
        Booklist.Add(New PremiumBook())
        Booklist.Add(New PremiumBook())
        Booklist.Add(New Book())

        For Each bk As Book In Booklist

            If bk.GetType() Is GetType(PremiumBook) Then 'If your collection contains multiple types, if not this check can be omitted
                Dim premiumBk As PremiumBook = DirectCast(bk, PremiumBook)
            End If

        Next

        Dim premiumBk2 As PremiumBook = DirectCast(Booklist(2), PremiumBook)


    End Sub

End Module

Upvotes: 1

Related Questions