Описание тега variance

In probability and statistics, the variance is a measure of the spread of a set of numbers.

In computer science, covariance and contravariance refers to the ordering of types from narrower to wider and their interchangeability or equivalence in certain situations.

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, the P is "larger" than C since it "contains" all the possible instances or objects or C, but can also contain some other objects 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: genetic 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 on P can also be applied to 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).

Variance in Mathematics

Variance is a descriptor of a probability distribution, it denotes how far away the numbers are from the expected value, the mean. The variance of a random variable or distribution is calculated as the mean of the squared deviation of that variable from its expected value or mean.

If a random variable X has the expected value (mean) μ = E[X] then the variance of X is given by:

enter image description here

or

enter image description here

See the Wikipedia article for more information.