Question

  public interface SomeInterfaceName<out T> where T : struct
  {
    T? SomePropertyName { get; }
  }

The error I get is:

error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'SomeInterfaceName.SomePropertyName'. 'T' is covariant.

I do not need this to be Covariant. I could as well delete the out keyword. But then Resharper is suggesting I could use Covariance and I agree, I don't see why I could not. I'm only using T as return value. Or is it because Nullable<> does not support it?

Can anybody explain the error?

Was it helpful?

Solution

It's pointless to make a type parameter with a struct constraint covariant. Generic variance isn't supported for value type type arguments at all - so for example, there's no conversion from IEnumerable<int> to either IEnumerable<long> or IEnumerable<object> even though there are conversions from int to both long and object.

The problem you're actually running into is that Nullable<T> isn't covariant, but you're trying to use T in a property of type Nullable<T>. That's what's causing the error.

Personally I think it would be better if type parameters with struct constraints couldn't be declared to be covariant or contravariant (given that it won't be useful) but that in itself isn't prohibited.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top