Question

I have the following sample code in a VB.NET console application. It compiles and works, but feels like a hack. Is there a way to define EmptyChild so that it inherits from Intermediate(Of T As Class) without using the dummy EmptyClass?

Module Module1
Sub Main()

    Dim Child1 = New RealChild()
    Child1.Content = New RealClass()
    Dim Child2 = New EmptyChild()

    Console.WriteLine("RealChild says: " & Child1.Test)
    Console.WriteLine("EmptyChild says: " & Child2.Test)
    Console.ReadLine()
End Sub

Public Class EmptyClass

End Class

Public Class RealClass

    Public Overrides Function ToString() As String
        Return "This is the RealClass"
    End Function

End Class

Public MustInherit Class Base(Of T As Class)

    Private _content As T = Nothing
    Public Property Content() As T
        Get
            Return _content
        End Get
        Set(ByVal value As T)
            _content = value
        End Set
    End Property

    Public Overridable Function Test() As String
        If Me._content IsNot Nothing Then
            Return Me._content.ToString
        Else
            Return "Content not initialized."
        End If
    End Function

End Class

Public MustInherit Class Intermediate(Of T As Class)
    Inherits Base(Of T)

    'some methods/properties here needed by Child classes

End Class

Public Class RealChild
    Inherits Intermediate(Of RealClass)

    'This class needs all functionality from Intermediate.

End Class

Public Class EmptyChild
    Inherits Intermediate(Of EmptyClass)

    'This class needs some functionality from Intermediate,
    ' but not the Content as T property.

    Public Overrides Function Test() As String
        Return "We don't care about Content property or Type T here."
    End Function

End Class
End Module

The other way to do this would be to move the generic code out of the Base class and then create 2 Intermediate classes like this:

Public MustInherit Class Intermediate
    Inherits Base

    'some methods/properties here needed by Child classes

End Class

Public MustInherit Class Intermediate(Of T As Class)
    Inherits Intermediate

    'implement generic Content property here

End Class

Then RealChild would inherit from the generic Intermediate and EmptyChild would inherit from the non-generic Intermediate. My problem with that solution is that the Base class is in a separate assembly and I need to keep the code that handles the generic type in that assembly. And there is functionality in the Intermediate class that does not belong in the assembly with the Base class.

Was it helpful?

Solution

Yes, you need to specify a type parameter when you inherit, or your EmptyChild must be generic as well. But, you don't have to dummy up a EmptyClass - just use Object as your type parameter:

 Public Class EmptyClass
    Inherits Intermediate(Of Object)
 End Class
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top