concept variance in category .net

This is an excerpt from Manning's book C# in Depth.
In section 2.2.2, we looked at the covariance of arrays—the fact that an array of a reference type can be viewed as an array of its base type, or an array of any of the interfaces it implements. There are actually two forms of this idea, called covariance and contravariance, or collectively just variance. Generics don’t support this—they’re invariant. This is for the sake of type safety, as you’ll see, but it can be annoying.
One thing I’d like to make clear to start with: C# 4 improves the generic variance situation somewhat. Many of the restrictions listed here do still apply though, and this section serves as a useful introduction to the idea of variance. We’ll see how C# 4 helps in chapter 13, but many of the clearest examples of generic variance rely on other new features from C# 3, including LINQ. Variance is also quite a complicated topic in itself, so it’s worth waiting until you’re comfortable with the rest of C# 2 and 3 before you tackle it. For the sake of readability, I won’t point out every place in this section that’s slightly different in C# 4...it’ll all become clear in chapter 13.
In essence, variance is about being able to use an object of one type as if it were another, in a type-safe way. You’re used to variance in terms of normal inheritance: if a method has a declared return type of Stream, you can return a MemoryStream from the implementation, for example. Generic variance is the same concept, but applied to generics, where it becomes a bit more complicated. The variance is applied to the type parameters within the interfaces and delegate types. That’s the bit you need to concentrate on.
Listing 13.12. Using variance to build a list of general shapes from specific lists
List<IShape> shapesByAdding = new List<IShape>(); #1 shapesByAdding.AddRange(circles); shapesByAdding.AddRange(squares); List<IShape> shapesByConcat = circles.Concat<IShape>(squares).ToList(); #2 #1 – 1 Adds lists directly #2 – 2 Uses LINQ for concatenation !@%STYLE%@! {"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":5,\"ch\":0},{\"line\":5,\"ch\":26}]]"} !@%STYLE%@!
You can’t use variance between two arbitrary type arguments just because there’s a conversion between them. It has to be a reference conversion. Basically, that limits it to conversions that operate on reference types and that don’t affect the binary representation of the reference. This is so that the CLR can know that operations will be type-safe without having to inject any actual conversion code anywhere. As I mentioned in section 13.3.2, variant conversions are themselves reference conversions, so there wouldn’t be anywhere for the extra code to go anyway.