using uint vs int [closed]

int is shorter to type than uint.


Your observation of why uint isn't used in the BCL is the main reason, I suspect.

UInt32 is not CLS Compliant, which means that it is wholly inappropriate for use in public APIs. If you're going to be using uint in your private API, this will mean doing conversions to other types - and it's typically easier and safer to just keep the type the same.

I also suspect that this is not as common in C# development, even when C# is the only language being used, primarily because it is not common in the BCL. Developers, in general, try to (thankfully) mimic the style of the framework on which they are building - in C#'s case, this means trying to make your APIs, public and internal, look as much like the .NET Framework BCL as possible. This would mean using uint sparingly.


Normally int will suffice. If you can satisfy all of the following conditions, you can use uint:

  • It is not for a public API (since uint is not CLS compliant).
  • You don't need negative numbers.
  • You (might) need the additional range.
  • You are not using it in a comparison with < 0, as that is never true.
  • You are not using it in a comparison with >= 0, as that is never false.

The last requirement is often forgotten and will introduce bugs:

static void Main(string[] args)
{
    if (args.Length == 0) return;
    uint last = (uint)(args.Length - 1);

    // This will eventually throw an IndexOutOfRangeException:
    for (uint i = last; i >= 0; i--)
    {
        Console.WriteLine(args[i]);
    }
}

1) Bad habit. Seriously. Even in C/C++.

Think of the common for pattern:

for( int i=0; i<3; i++ )
    foo(i);

There's absolutely no reason to use an integer there. You will never have negative values. But almost everyone will do a simple loop that way, even if it contains (at least) two other "style" errors.

2) int is perceived as the native type of the machine.


I prefer uint to int unless a negative number is actually in the range of acceptable values. In particular, accepting an int param but throwing an ArgumentException if the number is less than zero is just silly--use a uint!

I agree that uint is underused, and I encourage everyone else to use it more.