Why does .NET use int instead of uint in certain classes?

Viewed 5621

I always come across code that uses int for things like .Count, etc, even in the framework classes, instead of uint.

What's the reason for this?

7 Answers

UInt32 is not CLS compliant so it might not be available in all languages that target the Common Language Specification. Int32 is CLS compliant and therefore is guaranteed to exist in all languages.

int, in c, is specifically defined to be the default integer type of the processor, and is therefore held to be the fastest for general numeric operations.

If the number is truly unsigned by its intrinsic nature then I would declare it an unsigned int. However, if I just happen to be using a number (for the time being) in the positive range then I would call it an int.

The main reasons being that:

  • It avoids having to do a lot of type-casting as most methods/functions are written to take an int and not an unsigned int.
  • It eliminates possible truncation warnings.
  • You invariably end up wishing you could assign a negative value to the number that you had originally thought would always be positive.

Are just a few quick thoughts that came to mind.

I used to try and be very careful and choose the proper unsigned/signed and I finally realized that it doesn't really result in a positive benefit. It just creates extra work. So why make things hard by mixing and matching.

Some things use int so that they can return -1 as if it were "null" or something like that. Like a ComboBox will return -1 for it's SelectedIndex if it doesn't have any item selected.

Some old libraries and even InStr use negative numbers to mean special cases. I believe either its laziness or there's negative special values.

Related