August 26, 2004 1:58 pm

Satisfying and not satisfying constraints

Spent some more time on generic constraints. Some things are a bit surprising at first sight and so my first attempt to implement this was wrong:

interface IHello<t> { } class Foo<t> { public void Test<u> (IHello<u> hello) where U : T { } public void Ok<s> (IHello<s> hello) where S : T { Test (hello); } }

This example is ok and allowed - you may pass hello to that function since the constraints match. However, the following is not allowed:

class Hello<t> { } class Foo<t> { public static void Test<u> (Hello<u> a) where U : T { } } class X { } class Y : X { } class Z : Y { static void Main () { Hello<z> hello = new Hello<z> (); Foo<x>.Test<y> (hello); } }

The constraints just say that Y must derive from X - but this function still takes a Hello<Y> argument. You cannot interpret the constraints in a way that any generic instance Hello<T> is allowed, if just T derives from Y.

Posted by martin at August 26, 2004 1:58 pm.