Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are C# Lists indexed by signed int [duplicate]

Tags:

c#

.net

Possible Duplicates:
Why does .NET use int instead of uint in certain classes?
Why is Array.Length an int, and not an uint

I've always wonder why .Count isn't an unsigned integer instead of a signed one?

For example, take ListView.SelectedItems.Count. The number of elements can't be less then 0, so why is it a signed int?

If I try to test if there are elements selected, I would like to test

 if (ListView.SelectedItems.Count == 0) {}

but because it's a signed integer, I have to test

 if (ListView.SelectedItems.Count <= 0) {}

or is there any case when .Count could be < 0 ?

like image 241
Inno Avatar asked Sep 07 '10 12:09

Inno


3 Answers

Unsigned integer is not CLS-compliant (Common Language Specification)

For more info on CLS compliant code, see this link:

http://msdn.microsoft.com/en-us/library/bhc3fa7f.aspx

like image 154
Philippe Leybaert Avatar answered Sep 23 '22 13:09

Philippe Leybaert


Mabye because the uint data type is not part of the CLS (common language specification) as not all .Net languages support it.

Here is very similar thread about arrays:

Why is Array.Length an int, and not an uint

like image 34
nan Avatar answered Sep 22 '22 13:09

nan


Let’s look at this from a practical angle.

For better or worse, signed ints are the normal sort of ints in use in .NET. It was also normal to use signed ints in C and C++. So, most variables are declared to be int rather than unsigned int unless there is a good reason otherwise.

Converting between an unsigned int and a signed int has issues and is not always safe.

On a 32 bit system it is not possible for a collection to have anywhere close to 2^^32 items in it, so a signed int is big enough in all cases.

On a 64 bit system, an unsigned int does not gain you much, in most cases a signed int is still big enough, otherwise you need to use a 64 bit int. (I expect that none of the standard collection will cope well with anywhere near 2^^31 items on a 64 system!)

Therefore given that using an unsigned int has no clear advantage, why would you use an unsigned int?

like image 32
Ian Ringrose Avatar answered Sep 21 '22 13:09

Ian Ringrose