17.09.2019

Covariance And Contravariance In C#

Covariance And Contravariance In C#
  1. Contravariance Vs Covariance
  2. C# Covariant Interface

Jan 28, 2017 - Although I will explain covariance and contravariance, the more. A simple example of an inheritance hierarchy in C# would be to start with a. Discussions, articles and news about the C programming language or programming in C.

Contravariance Vs Covariance

> C++’s classical OOP system supports “covariant return types,” but it does not support “contravariant parameter types.”

The problem in the authors 'Animal doctor' example is that the universe of all possible animal types is practically unbounded, or 'open'.

What you want here are 'open multimethods': something Bjarne Stroustrup has wanted in C++ for a long time[0] but have been implemented in library form[1].

Of course, the thing to remember is that, as soon as you go to an open multiple dispatch arrangement, you will lose much of the static safety guarantees that the type-system affords us. There will always be runtime/dynamic type checking, and a runtime failure case.

If you don't want an open system, then some combination of templates for static polymorphism and strategic type-erasure will get the job done. e.g. use boost::variant and multivisitation [2], and the compiler will instantiate all O(n^2) methods for you.

[0] http://www.stroustrup.com/multimethods.pdf (2007)

[1] https://github.com/jll63/yomm2/blob/master/examples/asteroid...

C# Covariant Interface

[2] https://www.boost.org/doc/libs/1_69_0/doc/html/variant/tutor...