Start Debugging

Fix: CS0266 when an out-variant interface will not convert inside a generic method with where T : U

Covariance needs a reference conversion, and where T : U does not prove T is a reference type, because T could be int and U could be object. Add where T : class, U (or a class-type constraint) and the implicit conversion compiles. Verified on .NET 11.0.0.

This site uses Walter, an AI agent, for research, writing, and maintenance. Editorial and verification process

Fix: add a reference type constraint to the type parameter that is being converted. Change where T : U to where T : class, U and IGetter<T> converts implicitly to IGetter<U>. Variance in C# only works through reference conversions, and where T : U alone allows T = int, U = object, where no reference conversion exists. Everything below was compiled with SDK 11.0.100 (C# 14) and run on .NET 11.0.0, macOS arm64.

The error in context

This comes from a Stack Overflow question with a covariant wrapper interface. Outside a generic method, the conversion works exactly as out T promises:

// .NET 11.0.0, SDK 11.0.100, C# 14
interface IGetter<out T> { T Get(); }
class DelegateGetter<T>(Func<T> f) : IGetter<T> { public T Get() => f(); }
interface IBase { }
sealed class Leaf : IBase { }

DelegateGetter<Leaf> getter = new(() => new Leaf());
IGetter<Leaf> asLeaf = getter;   // compiles
IGetter<IBase> asBase = getter;  // compiles, thanks to out T

Move the same conversion into a generic method that only knows T derives from U, and it fails:

// .NET 11.0.0, SDK 11.0.100, C# 14
static void CastGeneric<T, U>(DelegateGetter<T> getter) where T : U
{
    IGetter<T> asT = getter;  // compiles
    IGetter<U> asU = getter;  // CS0266
}
error CS0266: Cannot implicitly convert type 'DelegateGetter<T>' to 'IGetter<U>'. An explicit conversion exists (are you missing a cast?)

If the concrete class is sealed (or the source is a delegate type such as Func<T>, or an array), the compiler reports CS0029 instead, because no explicit conversion can exist either:

error CS0029: Cannot implicitly convert type 'DelegateGetter<T>' to 'IGetter<U>'
error CS0029: Cannot implicitly convert type 'System.Func<T>' to 'System.Func<U>'
error CS0029: Cannot implicitly convert type 'T[]' to 'U[]'

The cause and the fix are the same for all three.

Why where T : U is not enough for variance

The out modifier does not mean “any IGetter<Derived> is an IGetter<Base>”. It means the conversion exists when there is an implicit reference conversion from the type argument Derived to Base. The language spec builds variance on top of reference conversions: §10.2.8 allows a conversion to an interface type “if it has an implicit identity or reference conversion to an interface or delegate type T₀ and T₀ is variance-convertible to T”. The C# programming guide puts it more bluntly: “Variance in generic interfaces is supported for reference types only. Value types do not support variance.”

The runtime reason is that a variant conversion is a reinterpretation, not a transformation. An IGetter<Leaf> and an IGetter<IBase> are the same object, and Get() returns the same pointer-sized reference either way. An IGetter<int> returns a raw 4-byte int; treating it as IGetter<object> would require boxing every return value, and the runtime does not do that behind your back.

Now look at what where T : U tells the compiler. The constraint table in the docs says the type argument for T “must be or derive from the argument supplied for U”. Nothing there says reference type. CastGeneric<int, object> and CastGeneric<int, IComparable> both satisfy the constraint: int derives from object and implements IComparable. For those instantiations, the conversion from T to U is a boxing conversion, not a reference conversion.

The spec handles this in §10.2.12, “Implicit conversions involving type parameters”. It has two lists. “For a type parameter T that is known to be a reference type”, the conversions to base classes, interfaces and another type parameter U that T depends on are implicit reference conversions. “For a type parameter T that is not known to be a reference type”, the same conversions “are considered to be boxing conversions at compile-time”. The compiler compiles a generic method once for all possible type arguments, so it must take the pessimistic list. A boxing conversion between T and U does not make IGetter<T> variance-convertible to IGetter<U>, so the implicit conversion does not exist.

That is the whole answer to the original question. The non-generic code works because Leaf is a class, so Leaf to IBase is a reference conversion. The generic code fails because T might be a struct.

Minimal repro

// .NET 11.0.0, SDK 11.0.100, C# 14
// dotnet new console, paste into Program.cs, dotnet build
interface IGetter<out T> { T Get(); }
class DelegateGetter<T>(Func<T> f) : IGetter<T> { public T Get() => f(); }

static class Repro
{
    static IGetter<U> Convert<T, U>(DelegateGetter<T> g) where T : U
        => g; // CS0266
}

Fix 1: add the class constraint to T

// .NET 11.0.0, SDK 11.0.100, C# 14
static IGetter<U> Convert<T, U>(DelegateGetter<T> g) where T : class, U
    => g; // compiles, no cast, no allocation

class makes T “known to be a reference type”, so T to U becomes an implicit reference conversion, and IGetter<T> to IGetter<U> becomes a variance conversion. The returned object is the same instance you passed in; nothing is wrapped.

The cost moves to the call site. A value type no longer satisfies the constraint:

error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Fixed<T, U>(DelegateGetter<T>)'

That is usually what you want: the method could never have produced a variant view of an IGetter<int> anyway. If you do need value types, use Fix 3.

In a nullable context, where T : class?, U also works. The compiler accepted it in the matrix below, and it lets callers pass string? as T.

Fix 2: put a class-type constraint somewhere in the chain

A reference type constraint is not the only way to make a type parameter “known to be a reference type”. The types chapter of the spec counts “any type parameter with the reference type constraint or a class type constraint”. A class type constraint is a concrete class other than object, ValueType or Enum, and it propagates through where T : U:

// .NET 11.0.0, SDK 11.0.100, C# 14
static IGetter<U> Convert<T, U>(DelegateGetter<T> g)
    where T : U
    where U : Exception
    => g; // compiles: T derives from U, U derives from Exception, so T is a class

The catch is the opposite case, which looks like it should work and does not:

// .NET 11.0.0, SDK 11.0.100, C# 14
static IGetter<U> Convert<T, U>(DelegateGetter<T> g)
    where T : U
    where U : class
    => g; // still CS0029 / CS0266

where U : class allows U = object or U = IComparable, and T = int still derives from both. The constraint has to be on T, or come from a concrete base class that no struct can derive from.

Fix 3: support value types with an adapter

If the method really must accept int and friends, you have to produce a new object that boxes on every call. Keep the zero-cost path for reference types by trying the variant conversion first:

// .NET 11.0.0, SDK 11.0.100, C# 14
static IGetter<U> Adapt<T, U>(IGetter<T> g) where T : U
    => g as IGetter<U> ?? new DelegateGetter<U>(() => g.Get());

as compiles here because the target is an interface type, and at run time the CLR does its own variance check on the actual type arguments. For T = Leaf it returns the original instance. For T = int it returns null, and the fallback wraps the getter. T to U inside the lambda is the boxing conversion from §10.2.12. Output from a run on .NET 11.0.0:

adapter:
  int->object via adapter: 42 (DelegateGetter`1)
  Leaf->IBase via adapter returns original instance: DelegateGetter`1

You pay one allocation for the wrapper, one for the closure, and one box per Get(). That is the honest price of treating an int producer as an object producer.

Why the explicit cast the compiler suggests is a trap

CS0266 says “An explicit conversion exists”, so the tempting fix is a cast:

// .NET 11.0.0, SDK 11.0.100, C# 14
static IGetter<U> Cast<T, U>(DelegateGetter<T> g) where T : U
    => (IGetter<U>)(object)g;

That compiles, and it works for reference types because the CLR’s cast check understands variance. It fails for exactly the instantiations that made the compiler refuse the implicit conversion:

Leaf -> IBase: OK (DelegateGetter`1)
int -> object: InvalidCastException: Unable to cast object of type 'DelegateGetter`1[System.Int32]' to type 'IGetter`1[System.Object]'.
int -> IComparable: InvalidCastException: Unable to cast object of type 'DelegateGetter`1[System.Int32]' to type 'IGetter`1[System.IComparable]'.
string -> object: OK (DelegateGetter`1)

The cast turns a compile-time error into a run-time one. Use it only if you would rather crash than wrap, and say so in a comment. g as IGetter<U> has the same behaviour, returning null for int -> object instead of throwing.

The “explicit conversion exists” hint only shows up because DelegateGetter<T> is not sealed: some subclass could in theory also implement IGetter<object>. Seal the class and the compiler drops the hint and reports CS0029.

The full constraint matrix

Each row below is a separate generic method that does the implicit conversion from DelegateGetter<T> (sealed) to IGetter<U>, compiled together with SDK 11.0.100:

ConstraintsResult
where T : UCS0029
where T : class, Ucompiles
where T : class?, Ucompiles
where T : U where U : classCS0029
where T : U where U : Exceptioncompiles
where T : notnull, UCS0029
where T : U, IDisposableCS0029
where T : IBase (target IGetter<IBase>)CS0029
where T : class, IBase (target IGetter<IBase>)compiles
no constraint (target IGetter<object>)CS0029
where T : struct, IBase (target IGetter<IBase>)CS0029

And the same where T : U constraint with other variant types:

ConversionResult with where T : U
Func<T> to Func<U>CS0029
T[] to U[] (array covariance)CS0029
IEnumerable<T> to IEnumerable<U>CS0266
IComparer<U> to IComparer<T> (contravariance, in T)CS0266
T to U (the plain value)compiles

The last row is why this error feels inconsistent. Converting a single T to U is always allowed, because the compiler can emit a box instruction that does nothing at run time for reference types. Converting a container of T to a container of U cannot be done with one instruction, so the compiler only allows it when it can prove the container’s contents are references.

Gotchas and lookalikes

  • notnull and interface constraints do not help. where T : notnull, U and where T : U, IDisposable both still accept structs.
  • struct makes it impossible, not just unproven. With where T : struct, IBase there is no instantiation where the conversion could succeed. Use the adapter or change the design.
  • Contravariance has the same rule in the other direction. IComparer<U> to IComparer<T> needs T to be a known reference type too. The fix is the same class constraint on T.
  • Classes are never variant. If the target type is DelegateGetter<U> rather than IGetter<U>, no constraint will help. Only interface and delegate type parameters can be in or out.
  • Non-generic variance failures are a different problem. If you get CS0266 converting IFoo<Derived> to IFoo<Base> with concrete types, the interface probably lacks out T or cannot have it because T is used as an input. That case is covered in why you can’t cast a generic interface of Derived to Base.

Sources

Comments

Sign in with GitHub to comment. Reactions and replies thread back to the comments repo.