T must be contravariantly valid

13,390

Solution 1

Consider what would happen if the compiler allowed that:

interface IR<out T>
{
    void D(T t);
}

class C : IR<Mammal>
{
    public void D(Mammal m)
    {
        m.GrowHair();
    }
}
...
IR<Animal> x = new C(); 
// legal because T is covariant and Mammal is convertible to Animal
x.D(new Fish()); // legal because IR<Animal>.D takes an Animal

And you just tried to grow hair on a fish.

The "out" means "T is only used in output positions". You are using it in an input position.

Solution 2

You can use an out type parameter only covariantly, i.e., in the return type. Therefore, IQueryable<T> GetAll() is correct, but void Delete(T t) is not.

Since T is used both co- and contravariantly in your class, you cannot use out here (nor in).

If you want to know more about the theoretical background behind this, take a quick break and read the "Covariance and Contravariance" Wikipedia article.


Welcome back. So, what do you do if you need all those methods in your repository but still need a covariant interface? You can extract the covariant part into its own interface:

interface IDataSource<out T> where T : IBusinessEntity
{
    IQueryable<T> GetAll();
}

interface IRepository<T> : IDataSource<T> where T : IBusinessEntity
{
    void Save(T t);
    void Delete(T t);
}

This is also how the .NET BCL solves this issue: IEnumerable<out T> is covariant, but only supports "read operations". ICollection<T> is a subtype of IEnumerable<out T>, allows read and write operations, and, thus, cannot be covariant itself.

Solution 3

The following two methods are wrong:

void Save(T t);
void Delete(T t);

You can't have T as method argument. Only as return type if you want it to be covariant (out T) in your generic definition.

Or if you want contravariance then you could use the generic parameter only as method argument and not return type:

interface IRepository<in T> where T : IBusinessEntity
{
    void Save(T t);
    void Delete(T t);
}
Share:
13,390
Eduardo
Author by

Eduardo

Updated on July 17, 2022

Comments

  • Eduardo
    Eduardo almost 2 years

    What is wrong with this?

    interface IRepository<out T> where T : IBusinessEntity
    {
        IQueryable<T> GetAll();
        void Save(T t);
        void Delete(T t);
    }
    

    It says:

    Invalid variance: The type parameter 'T' must be contravariantly valid on 'MyNamespace.IRepository.Delete(T)'. 'T' is covariant.

  • Jon Skeet
    Jon Skeet about 13 years
    Note that it can be in the parameters, but then only with something like an Action<T> which reverses the direction again.
  • amiry jd
    amiry jd over 12 years
    Complete and clean answer. Thanks
  • David
    David almost 9 years
    I could never understand why when explaining something, how T and IR and C and x are valid variable names. This also applies to MSDN documentation, especially with generics. What's "D"?
  • Eric Lippert
    Eric Lippert over 8 years
    @David: They are valid because they meet the criteria for identifiers in the C# specification, but I think you meant pedagogically valid. The pedagogy of using short names is to subtly remind the reader that this is a general, broadly applicable example that they should be thinking of in the abstract, and not a solution to a specific problem in a specific domain.
  • Luc-Olivier
    Luc-Olivier almost 5 years
    Not so pedagogically valid... when examples bring concept to mind while symbols bring significance that is far from conceptualization. But It's far from Variance.
  • Andrew Keeton
    Andrew Keeton over 4 years
    I wish I had seen this explanation when first trying to learn about co/contravariance: "The 'out' means 'T is only used in output positions'. You are using it in an input position." I had just assumed in and out were arbitrarily reused keywords.
  • Eric Lippert
    Eric Lippert over 4 years
    @AndrewKeeton: We went through a long design process where we considered a number of options. Like all design processes, there were many competing factors that had to be weighed against each other. See my 2007 article on the subject for some of the options and their pros and cons: blogs.msdn.microsoft.com/ericlippert/2007/10/31/…
  • Shelby115
    Shelby115 almost 4 years
    And now I finally understand why the keywords are in and out. Input to the class and output from the class. This has been a struggle for a while, thank you.
  • Peter Huber
    Peter Huber over 3 years
    @EricLippert: Why is bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value); not considered covariant ? Most IReadOnlyxxx interfaces like IReadOnlyList are covariant, but IReadOnlyDIctionary is not, because of TryGetValue. Shouldn't returning a value be treated the same as an out parameter ? Isn't an out parameter in an 'output position' ?
  • Eric Lippert
    Eric Lippert over 3 years
    @PeterHuber: Great follow-up question. Already answered here: stackoverflow.com/questions/2876315/… -- when designing new APIs like TryGetValue today, the best practice is to make them return a (bool, T) tuple instead of using an out parameter, and then this problem disappears.