Questions tagged [covariance]

Covariance, contravariance and invariance describe how the existing type inheritance hierarchy changes when subjected to some transformation (such as usage within generics). If the transformation keeps the ordering of the original hierarchy, it is "covariant". If it reverses it, it is "contravariant". If it breaks it, it is "invariant".

About Type Ordering

Let's say that a class P (parent) is inherited by a class C (child).

We can denote this fact as: P > C.

Informally, P is "larger" than C since it "contains" all the possible instances of C, but can also contain some other instances that are not C. Child is always parent but not necessarily the other way around.

Variance in Generics

Let's say that there is a generic type G that has a single generic parameter T, denoted by: G{T}.

  • If G{P} > G{C}, then T is co-variant (it preserves the original inheritance ordering).
  • If G{P} < G{C}, then T is contra-variant (it reverses the original inheritance ordering).
  • If G{P} and G{C} are type-unrelated, then T is invariant (it "breaks" the inheritance).

So the variance is the property of transformation (in this case: generic parameter T of G), not the original type hierarchy (P and C).

C# Examples

The generic parameter T of IEnumerable<out T> is covariant (as denoted by "out" keyword), meaning you can "forget" that the collection contains Cs and just treat it as if it contains Ps. For example:

IEnumerable<C> ec = ...;
IEnumerable<P> ep = ec;

The generic parameter T of Action<in T> is contravariant (as denoted by "in" keyword), meaning that an action that accepts P can also accept C. For example:

Action<P> ap = ...;
Action<C> ac = ap;

The generic parameter T is contravariant and generic parameter TResult is covariant in Func<in T, out TResult>. Each generic parameter is considered a different "transformation" with its own variance. This lets you write a code like this:

Func<P, C> fpc = ...;
Func<C, P> fcp = fpc;

And finally, the generic parameter T of IList<T> is considered invariant, so IList<P> and IList<C> are considered unrelated types (there is no assignment compatibility in either direction).


Tag usage

  • Do not use for the measurement of the strength and direction of the linear relationship between two random variables (statistical context). Instead, use other related tags, for example, .
    Moreover, consider whether the question might be better suited to Cross Validated, the Stack Exchange site for statistics, machine learning and data analysis.
1751 questions
0
votes
0 answers

Cannot wrap entity with interface because IDbSet interface is not covariant

I'm using entity framework database first and I faced a problem that I cannot solve elegantly. Let's say in my autogenerated entity I have some proprties that I don't want to use (or I don't want to allow somebody to use them). So I came up with a…
bakala12
  • 346
  • 1
  • 13
0
votes
1 answer

Virtual inheritance, explicit instantiation—returning derived class reference / pointer (covariant types)

.hpp template struct A { virtual A& modify() = 0; }; template struct B : virtual A {}; template struct C : B { C& modify() final; }; .cpp template C& C::modify() { // … …
0
votes
0 answers

Exporting regressions to latex with different covariance matrices in R

I would like to know if there is a way to use the stargazer package, or any other similar package, to export regression tables from R to latex using two different covariance matrices. When I say two different matrices I mean using both robust and…
Felipe Alvarenga
  • 2,140
  • 13
  • 31
0
votes
2 answers

Polymorphism, inheritance and generic C# : Cannot cast subclass into supertype

I have a problem with abstract class and generic in c# (I usually code in Java) : here is the code I would like to use : public interface InterfaceResult {...} public abstract class Result : InterfaceResult {...} public class ResultA : Result…
David
  • 57
  • 1
  • 6
0
votes
1 answer

Why can't class-wide upper-bound constraints be covariant and lower-bound constraints be contravariant in Hack?

Regardless of the variance of parameter on the left side, the constraints placed on Ta and Tb in the following declaration fail the typecheck: class A<+TCov, -TCon, [±]Ta as TCov, [±]Tb super TCon> { public function __construct(private Ta $ta,…
concat
  • 2,793
  • 11
  • 27
0
votes
1 answer

Covariance for classes with list members in C#

Consider a class hierarchy that looks as below. In essence, there is an abstract ComplexBase with some fields that are common to all classes. Then there is a ComplexClass derived from ComplexBase that, among other things, holds a collection of…
Informagic
  • 854
  • 1
  • 8
  • 21
0
votes
1 answer

calculate covariance matrix formula

I am trying to calculate 3d covariance matrix and I use this formula: But I got a different result when I use covariance matrix.vi in LabVIEW. This is the link to the .vi file and matrix data which include 3 columns for x1; x2;…
ThangNguyen
  • 351
  • 1
  • 3
  • 12
0
votes
2 answers

Numerical Matrix CSV -> Covariance Matrix

I have a CSV file containing a numerical matrix with over two thousand New York Stock Exchange listed companies' value over two years. It seems like it should be really simple - I want to attain a covariance matrix formed from the CSV matrix. As far…
lel23
  • 57
  • 7
0
votes
1 answer

How can members of IEnumerable be modified?

In an earlier question about generic variance, I was informed that members of IEnumerable can be modified. How can that be done and, seeing as variance violations arise when a covariant type can be modified, how then can IEnumerable be…
concat
  • 2,793
  • 11
  • 27
0
votes
1 answer

How can I convert AnyClass to AnyClass implicitly/Without recreating an object

I have a context in which I do not know what the specific type of my viewModel is, however, I have a base type of the viewModels. How would I convert my SomeClass to SomeClass without recreating the object? My signature of SomeClass is…
Mafii
  • 6,538
  • 1
  • 33
  • 52
0
votes
0 answers

Difficultly combining Interfaces, Abstract class, Delegates, Generics and Covariance

UPDATE: Thanks to some help it seems to be a bug with Unity's compiler as it doesn't happen outside of Unity. I am currently submitting a bug report and I'll try and find a work around. I originally posted this to reddit but I think I will need…
0
votes
1 answer

Why can't a class with a type parameter used exclusively as an argument type be covariant on it?

The most common example I have found to explain why contravariantly-valid type parameters cannot be used covariantly has involved constructing some read-write wrapper of a derived type, casting it to a wrapper of the base type, injecting a different…
concat
  • 2,793
  • 11
  • 27
0
votes
1 answer

DataGridView with covariance?

I have code like below (I've generified and reduced it to represent just the issue at hand). The code works, that is it takes in a DataGridView.DataSource and ulitmately, using EPPlus, outputs the data to an Excel file. My question relates to…
Al Lelopath
  • 5,810
  • 12
  • 66
  • 120
0
votes
1 answer

Is it a mistake in msdn documentation for covariance at delegates?

In this msdn documentation about covariance and contravariance it is explained that out keyword is used to declare a generic parameter covariant. You can declare a generic type parameter covariant by using the out keyword. Then is given an example…
meJustAndrew
  • 4,755
  • 4
  • 40
  • 63
0
votes
1 answer

Simulate making library interfaces variant

There are several places where my code significantly benefits from using variance to take better advantage of polymorphism. What I would really like to do, which I know is not possible, is something like this: abstract class A { // In my perfect…
hypehuman
  • 1,184
  • 1
  • 16
  • 35
1 2 3
99
100