Created
May 23, 2018 15:40
-
-
Save jotatoledo/4a8c9df62822429b33889f395b92a163 to your computer and use it in GitHub Desktop.
Explanation of covariance and contravariance in C#
This file contains 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
// Assignment compatibility. | |
string str = "test"; | |
// An object of a more derived type is assigned to an object of a less derived type. | |
object obj = str; | |
// Covariance. | |
IEnumerable<string> strings = new List<string>(); | |
// An object that is instantiated with a more derived type argument | |
// is assigned to an object instantiated with a less derived type argument. | |
// Assignment compatibility is preserved. | |
IEnumerable<object> objects = strings; | |
// Contravariance. | |
// Assume that the following method is in the class: | |
// static void SetObject(object o) { } | |
Action<object> actObject = SetObject; | |
// An object that is instantiated with a less derived type argument | |
// is assigned to an object instantiated with a more derived type argument. | |
// Assignment compatibility is reversed. | |
Action<string> actString = actObject; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment