Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Unsigned Primitive Types

Most of time we represent concepts which can never be less than 0. For example to declare length, we write:

int length;

The name expresses its purpose well but you can assign negative values to it. It seems that for some situations, you can represent your intent more clearly by writing it this way instead:

uint length; 

Some disadvantages that I can think of:

  • unsigned types (uint, ulong, ushort) are not CLS compliant so you can't use it with other languages that don't support this
  • .Net classes use signed types most of the time so you have to cast

Thoughts?

like image 786
jfs Avatar asked Aug 29 '08 02:08

jfs


2 Answers

“When in Rome, do as the Romans do.”

While there is theoretically an advantage in using unsigned values where applicable because it makes the code more expressive, this is simply not done in C#. I'm not sure why the developers initially didn't design the interfaces to handle uints and make the type CLS compliant but now the train has left the station.

Since consistency is generally important I'd advise taking the C# road and using ints.

like image 185
Konrad Rudolph Avatar answered Sep 27 '22 15:09

Konrad Rudolph


If you decrement a signed number with a value of 0, it becomes negative and you can easily test for this. If you decrement an unsigned number with a value of 0, it underflows and becomes the maximum value for the type - somewhat more difficult to check for.

like image 29
Shog9 Avatar answered Sep 27 '22 16:09

Shog9