#1,048 – No Implicit Conversions between Signed vs. Unsigned

You can do an implicit numeric conversion when the conversion would not result in the loss of data.

You can never do an implicit conversion to convert between the signed vs. unsigned variants of a particular type, e.g. between short and ushort.

This makes sense, because the ranges of the signed vs. unsigned types overlap, but one is not inclusive of the other.  For example:

  • short :  -32,768 to 32,767
  • ushort :  0 to 65,535

You can’t do an implicit conversion between these types, in either direction.

You can, however, convert between these types using an explicit conversion (with a cast operator).  If the value to be converted is not representable in the target type, data will be lost but the assignment will succeed.  (How explicit casts fail).

            ushort myUnsignedShort = 40000;
            short myShort;

            // Compiles, but data is lost on
            // assignment
            myShort = (short)myUnsignedShort;

            // Now we'll get OverflowException
            myShort = checked((short)myUnsignedShort);

Here’s what the data looks like after the first assignment:
1048-001

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #1,048 – No Implicit Conversions between Signed vs. Unsigned

  1. Anonimous says:

    If you are casting integer number between signed and unsigned types but with the same size, then data will _NOT_ be lost. Only representation for human will be changed. Cast between following types are safe: byte and sbyte; short and ushort; int and uint; long and ulong.

    ushort myUnsignedShort = 40000;

    short myShort = (short)myUnsignedShort;

    // anotherUnsignedShort == 40000
    ushort anotherUnsignedShort = (ushort)myShort;

    // and magic 😉
    // magicUnsignedShort == 40002
    ushort magicUnsignedShort = (ushort)(myShort + 2);

    P.S. Links to articles about binary representation of integer numbers, adder–subtractor circuit and exotic processor architecture will be very useful.

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 )

Connecting to %s

%d bloggers like this: