Thursday, September 16, 2010

Why not use uint?

Why is List.Length an int, and not an unit? This bothers me (just a bit), because a length value can never be negative, can it? You will never have Length property return you a value which is less than 0.

So the questions is: Is there any use for an unsigned int (unit)? Even Microsoft seems not to use it.

One of my old friends writing a class with several methods that take integer input. The input values cannot be less than zero. Since we are not on .Net 4.0 yet, he is manually writing code contracts (that is, the function checks preconditions, i.e. before doing anything else, actual value is checked)

if (EngineNumber < 3)
   throw new ArgumentOutofRangeException("EngineNumber", "Engine number must be 3 or greater");

This got me thinking: why don't we ever use unsigned integers? Seems like have a uint would better communicate the requirement, and would simply not allow a negative number. The main answer seems to be that casting between uint and other data types, which is inevitable, is ugly. And that uint is not CLS compliant.

Recent Posts