C
C#5mo ago
Sn9800

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! 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...
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server