views:

70

answers:

3

Whats the rationale for using signed numbers as indexes in .Net?

In Python, you can index from the end of an array by sending negative numbers, but this is not the case in .Net. It's not easy for .Net to add such a feature later as it could break other code perhaps using special rules (yeah, a bad idea, but I guess it happens) on indexing.

Not that I have ever have needed to index arrays over 2,147,483,647 in size, but I really cannot understand why they choose signed numbers.

Can it be because it's more normal to use signed numbers in code?

Edit: I just found these links:

The perils of unsigned iteration in C/C++

Signed word lengths and indexes

Edit2: Ok, a couple of other good reasons from the thread Matthew Flaschen posted:

  • Historical reasons as it's a c-like language
  • Interop with c
+2  A: 

Unsigned isn't CLS compliant.

ho1
But Microsoft made the CLS specs right? They had the final say in this case and they did choose to use signed numbers.
Blindy
@Blindy: I think they wanted to make the CLS specs as inclusive as possible, and not all languages support unsigned numbers (for example VB6 and even if VB6 isn't a CLS language I suppose they might have wanted to increase the chance of interoperability).
ho1
+2  A: 

It may be to the long tradition of using a value below 0 as an invalid index. Methods like String.IndexOf return -1 if the element is not found. Therefore, the return value must be signed. If index-consumers would require unsigned values, you would have to a) check and b) cast the value to use it. With signed indices, you just need the check.

Arne
Seems plausible, but that's the only example I can think of. Using a negative number as an index is a runtime error. IndexOf could have been implemented another way.
simendsjo
Another example is [List<T>.BinarySearch](http://msdn.microsoft.com/en-us/library/w4e7fxsh.aspx) where the return is "The zero-based index of item in the sorted List<T>, if item is found; otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of Count."
Robert Paulson
+2  A: 

For simplicity of course. Do you like trouble doing size arithmetic with unsigned ints?

Rotsor
A very good and valid point
simendsjo