rcp rcp - 4 months ago 42
Vb.net Question

VB.NET Subclass of class containing list collection of subclassed items

Consider a class named Fruit and a class named FruitStand which contains a generic List of Fruit and exposes a property (Contents) to obtain the List of Fruit for the pupose of iterating the Fruit in the class.

Now I want to create a class Apple that is a subclass of Fruit and I want a class called AppleCart that is a subclass of FruitStand. The contents of the generic List in AppleCart will only ever contain intances of the Apple class. What I want is to be able to have a consumer of AppleCart not have to cast the elements returned by the Contents property to Apple from Fruit.

I am hoping this is something simple that I am just having a mental block over.


You could use generics.

Sub Main()

    Dim cart As New AppleCart

    cart.Fruits.Add(New Apple)

End Sub

Class FruitStand(Of T As Fruit)

    Public Property Fruits As List(Of T)

End Class

Class Fruit

End Class

Class AppleCart
    Inherits FruitStand(Of Apple)

End Class

Class Apple
    Inherits Fruit

End Class