#1,048 – No Implicit Conversions between Signed vs. Unsigned
March 7, 2014 1 Comment
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);
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.