#570 – Assignment Compatibility for Reference Types

A reference type is assignment compatible if the value being assigned belongs to a type that is either the same as, or is a derived type of, the type of the storage location being assigned to.  You can assign a variable of type T to a storage location of type U if T is a narrower type than U, or is the same type as U.

Hound huck = new Hound("Huckleberry", 55);

// Since Hound is a sub-class of Dog, we can
// assign to a variable of type Dog
Dog dog1 = huck;

In this case, the variable of type Dog will still be pointing to an instance of a Hound.  The assignment doesn’t change anything about the object.

To see this, construct an instance of a Dog directly and then compare the objects.

// This one points to an actual Dog instance
Dog dog2 = new Dog("Just some dog", 2);

Advertisement

#569 – Assignment Compatibility

The idea of assignment compatibility in C# is the idea that you can store a value that has a particular type into a storage location (variable) of a different type without losing any data.  (The conversion is “representation-preserving“).

So we can say that type T is assignment compatible with type U if we can store values of type T into variables of type U.

For value types, a type T will typically be assignment compatible with another type U, if T can represent a subset of the values that U can represent.  T can be thought of as “smaller” or “narrower” than U.

// byte is assignment compatible with ushort
byte n1 = 123;    // byte: 0-255
ushort n2 = n1;   // ushort: 0-65535

As you’d expect, a type is always assignment compatible with itself:

            byte n1 = 123;
            byte n2 = n1;