Skip to content

Instantly share code, notes, and snippets.

@drguildo
Last active February 4, 2020 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drguildo/d390d14210e3f9366d883e56f7a66aad to your computer and use it in GitHub Desktop.
Save drguildo/d390d14210e3f9366d883e56f7a66aad to your computer and use it in GitHub Desktop.
Covariance and contravariance.
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