Sn9800
Sn9800
CC#
Created by Sn9800 on 6/11/2024 in #help
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
1 replies