Question Details

No question body available.

Tags

c# generics

Answers (1)

Accepted Answer Available
Accepted Answer
July 17, 2026 Score: 3 Rep: 4,668 Quality: High Completeness: 80%

In your Generic method, T can be a value type (for example int) and U an interface (for example IComparable or object)

In C# documentation (https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/covariance-contravariance/variance-in-generic-interfaces), it says

Variance in generic interfaces is supported for reference types only. Value types do not support variance. For example, IEnumerable cannot be implicitly converted to IEnumerable, because integers are represented by a value type.

I believe the reason it doesn't work for value types is due to difference in memory layout and the need of boxing/unboxing.

To fix your problem the compiler has to make sure that T must be a class (which implies that U is also a class since T inherits U).

Here is how to fix it:

private static void CastGeneric(DelegateGetter delegateGetter) where T: class, U { IGetter castToLeaf = delegateGetter; // Compiles IGetter castToInterface = delegateGetter; // Compiles }