O'Reilly logo

Functional Programming in C#: Classic Programming Techniques for Modern Projects by Oliver Sturm

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

COVARIANCE AND CONTRAVARIANCE

The topic of variance is complex because it applies to many different code constructs. Designers of programming language make (hopefully conscious) decisions to support variance in a variety of different scenarios, or not to do so.

There is a distinction being made between covariance and contravariance. Very roughly, an operation is covariant if it preserves the ordering of types, and contravariant if it reverses this order. The ordering itself is meant to represent more general types as larger than more specific types.

Here’s one example of a situation where C# supports covariance. First, this is an array of objects:

object[] objects = new object[3];

objects[0] = new object( );

objects[1] = "Just a string";

objects[2] = 10;

Of course it is possible to insert different values into the array because in the end they all derive from Object in .NET. In other words, Object is a very general or large type. Now here’s a spot where covariance is supported: assigning a value of a smaller type to a variable of a larger type.

string[] strings = new string[] { "one", "two", "three" };

objects = strings;

The variable objects, which is of type object[], can store a value that is in fact of type string[]. Think about it — to a point, it’s what you expect, but then again it isn’t. After all, while string derives from object, string[] doesn’t derive from object[]. The language support for covariance in this example makes the assignment possible anyway, which is ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required