Last active
February 4, 2020 09:29
-
-
Save drguildo/d390d14210e3f9366d883e56f7a66aad to your computer and use it in GitHub Desktop.
Covariance and contravariance.
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
static void SetObject(object o) { } | |
void Main() | |
{ | |
// 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. | |
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; | |
// Covariance for arrays enables implicit conversion of an array of a more | |
// derived type to an array of a less derived type. But this operation is | |
// not type safe. | |
object[] array = new String[10]; | |
// The following statement produces a run-time exception. | |
// array[0] = 10; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment