Question

Is there any way to call to get the call to Me.DoSomething2 inside of MainApplication.CallDoSomething to work in the code below.

Public Interface ICovariance(Of Out T As Grandparent) 
End Interface
Public MustInherit Class Grandparent
End Class
Public Class Parent : Inherits Grandparent
End Class
Public Class Child : Inherits Parent
End Class
Public Class CustomList(Of T As Grandparent) : Implements ICovariance(Of T)
End Class
Public Class CustomList2(Of T As Parent)
    Inherits CustomList(Of T)

    Public Sub MyCustomList2Method()
    End Sub
End Class
Public Class MainApplication
    Public Sub CallDoSomething()
        'This Works
        Me.DoSomething(Of CustomList2(Of Child))()

        'This does not work
         Me.DoSomething2(Of CustomList2(Of Child))()
    End Sub

    ' This method works because of the interface and covariance 
    Public Function DoSomething(Of T As {ICovariance(Of Grandparent), New})() As T
        Dim instance As New T

        'This method can't be called because I'm working with an interface
        instance.MyCustomList2Method()
        Return instance
    End Function

    ' This method does not work. 
    ' I want T to be a CustomList2 that contains Parent 
    ' (or anything that inherits Parent)
    Public Function DoSomething2(Of T As {CustomList2(Of Parent), New})() As T
        Dim instance As New T

        'This method would work if I could call this method
        instance.MyCustomList2Method()

        Return instance
    End Function
End Class

I understand that that type parameters on DoSomething2 are expecting a CustomList2(Of Parent), but I'd like to pass a Customlist2(Of Child) to it. I can get this to work with an interface that uses covariance. Using an interface does not allow me toe call methods, such as CustomList2.MyCustomerList2Method.

This is a simplified example Could anyone provide some insight?

Was it helpful?

Solution

Try adding second generic type parameter to your second method:

Public Function DoSomething2(Of T1 As {Parent}, T2 As {CustomList2(Of T1), New})() As T2
    Dim instance As New T2

    'This method would work if I could call this method
    instance.MyCustomList2Method()

    Return instance
End Function

When it looks like that, you can call it like this:

Me.DoSomething2(Of Child, CustomList2(Of Child))()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top