views:

20

answers:

1

Hello,

I have a base class (ex: Class1) containing a list of another base class (ex: ClassA). Each child class of first base class (ex: Class1AA, Class1AB,..) containing a list of child class of second base class (ex: ClassAA, ClassAB,...)

The client must never know which child class is using, then i don't think i can use generic for my bases classes.

I try something like this and many more, but i always received errors..

Imports System.Collections.Generic

Public Class Client

    Public Sub DoAction(obj as Class1)
        For Each item as ClassA in obj.ItemList
        ...
        Next
    End Sub

End Class

Public MustInherit Class Class1
    Public MustOverride ReadOnly Property ItemList() As IList(Of ClassA)

End Class

Public Class Class1AA
    Inherits Class1

    Public Overrides ReadOnly Property ItemList() As IList(Of ClassA)
        Get
            Return New List(Of ClassAA)
        End Get
    End Property
End Class

Public Class Class1AB
    Inherits Class1

    Public Overrides ReadOnly Property ItemList() As IList(Of ClassA)
        Get
            Return New List(Of ClassAB)
        End Get
    End Property
End Class

Public Class ClassA

End Class

Public Class ClassAA
    Inherits ClassA

End Class

Public Class ClassAB
    Inherits ClassA

End Class

Thanks for your help

+1  A: 

This code would require generic covariance which doesn’t exist in VB.

Basically there is no relation between a List(Of Base) and a List(Of Derived). Otherwise, the following code could be written:

Dim a As New List(Of Base)()
a.Add(New Base())

Dim b As List(Of Derived) = a
''// Can’t work: b(0) doesn’t contain a `Derived` instance!
Dim x As Derived = b(0)

However, you can simply return a List(Of ClassA) everywhere and put derived objects into that list.

Konrad Rudolph
I think you meant "return value covariance"
JaredPar
@Jared: no – return value covariance also concerns compatibility of delegate types, and VB *has* this. What I meant was covariance of generic types. I thought that was called “generic covariance”. At least I’m not the only one who’s using it that way, according to almighty Google. ;-)
Konrad Rudolph
@Konrad it looks like the OP is asking to have the child property return `List(Of Child)` instead of `List(Of Parent)` (legal in C++). I thought that was termed "return value covariance"
JaredPar
@Jared: It’s not legal in C++ either. You’re thinking of returning `Child` instead of `Parent` – *that* would be legal and indeed, that would be return value covariance.
Konrad Rudolph
@Konrad, gotcha. I get the difference now.
JaredPar
Thanks for the anwser.
Kipotlov