Search code examples
c#genericscovariancecontravariancevariance

Type parameters defining each other? class A<T1, T2> where T1 : Foo where T2 : T1


Does

class A<T1, T2>
    where T1 : Foo
    where T2 : T1

have an actual use case?

What's the difference to

class A<T1, T2>
    where T1 : Foo
    where T2 : Foo

? What does actually change?

Is it the same when variance is involved?


Solution

  • The difference is that T2 cannot be just any Foo it has to be a Foo that is derived from T1.

    For instance

    public class Foo{}
    public class Foo1 : Foo {}
    public class Foo2 : Foo {}
    public class Foo12 : Foo1 {}
    public class A<T1,T2> where T1: Foo where T2 : T1 {}
    

    will allow

    var a = new A<Foo1, Foo12>()
    

    but not

    var a  = new A<Foo1, Foo2>()
    

    This also means that you can safely cast an object of type T2 to T1.

    Is it the same when variance is involved?

    Variance only comes into play with interfaces.