Converting from generic type to its constraint interface

I have created a generic class, with the constraint IComparable, as follows:

Public Class Foo(Of T As IComparable)
    Private _f As T

    Public Sub New(ByVal f As T)
        _f = f
    End Sub

    Public Function GetBar() As Bar
        Return New Bar(Me) 'compiler error: Value of type Foo(of T) 
                           'cannot be converted to Foo(of IComparable)
    End Function

End Class

I have another class which takes as a constructor argument an object of the first class defined:

Public Class Bar
    Private _foo As Foo(Of IComparable)

    Public Sub New(ByVal foo As Foo(Of IComparable))
        _foo = foo
    End Sub
End Class

However, I get the shown error when trying to create the Bar object.

Can anybody explain why am I getting this error? I would expect the compiler to know that type T is any IComparable type...

I have found a similar question here, but I don't know how to use it in my case.

Jon Skeet
people
quotationmark

I would expect the compiler to know that type T is any IComparable type...

Yes, it knows that - but your Bar constructor is expecting a Foo(Of IComparable) not a Foo(Of T) where T implements IComparable. You want generic covariance, but that can't be applied to classes in .NET (only interfaces and delegates).

One option is to make Bar generic as well, with another type parameter T which is constrained to implement IComparable. Then your Foo.GetBar() method could return a Bar(Of T).

people

See more on this question at Stackoverflow