© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago
sonnguyen9800

Help on Covariance and Contravariance in C#

Hi there! I am trying to understand Covariance and Contravariance. Now I am thinking about why In and Out permitted only generic class T in parameter and output only? I found this example of Eric Lippert on stackoverflow to be great to illustrate why T in parameter for Out is impossible

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!
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!



I try to come up with an equivalent to Contravariance but I couldn't. Please help me. I somehow think that Contravariance with T as output is not impossible as the case with Covariance and T in parameter. :nekoknife:

Link the original stackoverflow: https://stackoverflow.com/a/5043054/25500815
Stack Overflow
T must be contravariantly valid
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: Th...
T must be contravariantly valid
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ Covariance and Contravariance C#
C#CC# / help
3y ago
✅ Covariance & Contravariance
C#CC# / help
3y ago
help in c#
C#CC# / help
2y ago
✅ C# and CGI Help
C#CC# / help
3y ago