#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;
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #569 – Assignment Compatibility

  1. Pingback: #570 – Assignment Compatibility for Reference Types « 2,000 Things You Should Know About C#

  2. Garrett Forestwood says:

    Great explanation Sean!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: