Created
February 12, 2025 11:19
-
-
Save En3Tho/999767f70c78758b7ed02ed153a6824a to your computer and use it in GitHub Desktop.
Co(ntra)variance cheatsheet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| interface ICovariant<out T>; | |
| interface IContravariant<in T>; | |
| interface IConcrete<T>; | |
| class Foo1; | |
| class Foo2 : Foo1, ICovariant<Foo2>, IContravariant<Foo2>, IConcrete<Foo2>; | |
| class Foo3 : Foo2; | |
| static void Test() | |
| { | |
| Foo2 foo = new(); | |
| ICovariant<object> cov1 = foo; // ok | |
| ICovariant<Foo> cov2 = foo; // ok | |
| ICovariant<Foo2> cov3 = foo; // ok | |
| ICovariant<Foo3> cov4 = foo; // error | |
| // | covariance(Foo2) | | |
| // | supertypesOf(Foo2) | | |
| IContravariant<object> cov1 = foo; // error | |
| IContravariant<Foo> cov2 = foo; // error | |
| IContravariant<Foo2> cov3 = foo; // ok | |
| IContravariant<Foo3> cov4 = foo; // ok | |
| // | contravariance(Foo2) | | |
| // | subtypesOf(Foo2) | | |
| // object => Foo => Foo2 => Foo3 => ... | |
| // | | |
| // invariance(Foo2) | |
| // typeof(Foo2) | |
| IConcrete<object> inv1 = foo; // error | |
| IConcrete<Foo1> inv2 = foo; // error | |
| IConcrete<Foo2> inv3 = foo; // ok | |
| IConcrete<Foo3> inv4 = foo; // error | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment