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:
A signed integer is a 32-bit datum that encodes an integer in the range [-2147483648 to 2147483647]. An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295].
An unsigned number contains just zero or positive values, whereas a signed number has both positive and negative numbers along with the value zero. The maximum value of signed numbers is half that of unsigned numbers.
Unsigned integers are used when we know that the value that we are storing will always be non-negative (zero or positive). Note: it is almost always the case that you could use a regular integer variable in place of an unsigned integer.
Both can store 256 different values, but signed integers use half of their range for negative numbers, whereas unsigned integers can store positive numbers that are twice as large. An n-bit unsigned variable has a range of 0 to (2n)-1.
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.
For simplicity of course. Do you like trouble doing size arithmetic with unsigned ints?
Unsigned isn't CLS compliant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With