On C# 4, co/contra-variance and generic constraints

While trying to clean up some code today, I stumbled upon interesting result of certain refactoring.

Given the following covariant interface and its implementation:

 

public interface IReference<out T> { }

public class ComponentReference<T> : IReference<T> { }

and the following usage:

public static IReference<IInterceptor> ForType<T>() where T : IInterceptor

{

    return new ComponentReference<T>();

}

the code won’t compile. However, not all is lost – if you cast explicitly, everything will work just fine:

public static IReference<IInterceptor> ForType<T>() where T : IInterceptor

{

    return (IReference<IInterceptor>)new ComponentReference<T>();

}