0

I have a simple piece of code as follows:

Public Interface ITest(Of T)
    Function getObj() As T
End Interface

Public Class clsTest(Of T As {IOrder, New})
    Implements ITest(Of T)
    Public Function getObj() As T Implements ITest(Of T).getObj
        Return New T
    End Function
End Class

Public Interface IOrder
    Property Name As String
End Interface

Public Class clsOrder
    Implements IOrder
    Public Property Name As String Implements IOrder.Name
End Class

When I create a clsTest object like:

Dim test As ITest(Of IOrder) = New clsTest(Of clsOrder)

I got the following error:

'ConsoleApplication1.clsTest(Of ConsoleApplication1.clsOrder)' cannot be converted to 'ConsoleApplication1.ITest(Of ConsoleApplication1.IOrder)'. Consider changing the 'T' in the definition of 'Interface ITest(Of T)' to an Out type parameter, 'Out T'.

Anyone knows the reason? If I do want declare the test as ITest(Of IOrder), how can I make it work? Thanks.

beerwin
  • 9,813
  • 6
  • 42
  • 57
FrankS
  • 1

1 Answers1

0

Make your interface covariant in T with the Out-keyword:

Public Interface ITest(Of Out T)
    Function getObj() As T
End Interface

Then this will compile:

Dim test As ITest(Of IOrder) = New clsTest(Of clsOrder)

E. Lippert can explain it better than me:

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939