I'm trying to understand how covariance works with generic type constraints and it seems like the constraints are ignored for no obvious reason.
Consider the following code:
public interface IContainer<out T> { }
public interface IContents { }
public class Food : IContents { }
public class Foo
{
public void Bar<T>() where T : IContents
{
IContainer<IContents> x = null;
IContainer<T> y = null;
IContainer<Food> z = null;
x = y; // Cannot convert source type 'IContainer<T>' to target type 'IContainer<IContents>'
x = z; // Valid
}
}
Why does compiler produce 'Cannot convert' error on x = y and produce no error on x = z?