Search code examples
.netvb.netoopgenericsclr

Can a generic version of a derived class override a base method using the generic type?


Consider:

Public MustInherit Class Column
    Public ReadOnly Property ReturnSomethingUseful() As Object
        Get
             'return something useful
        End Get
    End Property
End Class

Public Class TypedColumn(Of T)
    Inherits Column

    Public Overrides ReadOnly Property ReturnSomethingUseful() As T
        Get
             'return the same something useful, but as type T
             Return MyBase.ReturnSomethingUseful()
        End Get
    End Property
End Class

But this gives the following error:

Public Overrides Function ReturnSomethingUseful(sValue As String) As Boolean' cannot override 'Public Overridable Function ReturnSomethingUseful(sValue As String) As Object' because they differ by their return types.

I accept that you can't do this, but I'd like to be able to preserve the semantics of what I'm trying to do, which is to have an untyped version that deals with Object, but a typed version in derived classes that knows about the specific type T. Is there any way to accomplish this?


Solution

  • I don't love this answer, but here's what I'm doing until I can find a truly elegant solution to this problem:

    Public Class TypedColumn(Of T)
        Inherits Column
    
        Public ReadOnly Property ReturnSomethingUsefulTyped() As T
            Get
              'return the same something useful, but as type T
              Return MyBase.ReturnSomethingUseful()
            End Get
        End Property
    End Class
    

    So instead of overriding the base method, it's just got a different name that indicates what it does. Not wonderful, but better than dealing with type Object and also better than the problems with Shadows.