concept reference conversion in category .net

appears as: reference conversions, reference conversion
C# in Depth

This is an excerpt from Manning's book C# in Depth.

You may already be aware that C# 4 offers generic covariance and contravariance for delegates and interfaces. This is entirely different from the variance we’re looking at here—we’re only dealing with creating new instances of delegates at the moment. The generic variance in C# 4 uses reference conversions, which don’t create new objects—they just view the existing object as a different type.

Any conversion using variance or covariance is a reference conversion, which means that the same reference is returned after the conversion. It doesn’t create a new object; it just treats the existing reference as if it matched the target type. This is the same as casting between reference types in a hierarchy: if you cast a Stream to MemoryStream (or use the implicit conversion the other way), there’s still just one object. The nature of these conversions introduces some limitations, as you’ll see later, but it means they’re efficient, and it makes the behavior easier to understand in terms of object identity.

Variance only supports reference conversions

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.