Tutorial :Why are the unsigned CLR types so difficult to use in C#?



Question:

I came from a mostly C/C++ background before I began using C#. One of the things I did with my first project in C# was make a class like this

class Element{    public uint Size;    public ulong BigThing;  }  

I was then mortified by the fact that this requires casting:

int x=MyElement.Size;  

as does

int x=5;  uint total=MyElement.Size+x;  

Why did the language designers decide to make the signed and unsigned integer types not implicitly castable? And why are the unsigned types not used more throughout the .Net library? For instance String.Length can never be negative, yet it is a signed integer.


Solution:1

Why did the language designers decide to make the signed and unsigned integer types not implicitly castable?

Because that could lose data or throw any exception, neither of which is generally a good thing to allow implicitly. (The implicit conversion from long to double can lose data too, admittedly, but in a different way.)

And why are the unsigned types not used more throughout the .Net library

Unsigned types aren't CLS-compliant - not all .NET languages have always supported them. For example, Visual Basic didn't have "native" support for unsigned data types in .NET 1.0 and 1.1; it was added to the language for 2.0. (You could still use them, but they weren't part of the language itself - you couldn't use the normal arithmetic operators, for example.)


Solution:2

Along with Jon's answer, just because an unsigned number can't be negative doesn't mean it isn't bigger than a signed one. uint is 0 to 4,294,967,295 but int is -2,147,483,648 to 2,147,483,647. Plenty of room above int's max for loss.


Solution:3

Because implicitly converting an unsigned integer of 3B into an signed integer is going to blow up.

Unsigned has twice the maximum value of signed. It's the same reason you can't cast a long to an int.


Solution:4

I was then mortified by the fact that this requires casting:

 int x=MyElement.Size;  

But you are contradicting yourself here. If you really (really) need Size to be unsigned than assigning it to (signed) x is an error. A deep flaw in your code.

For instance String.Length can never be negative, yet it is a signed integer

But String.IndexOf can return a negative number, and it would be awkward if String.Length and Index values where of different types.

And while in theory there would be merit in an unsigned String.Length (4 GB cap), in practice even the current 2GB is large enough (because strings of that length are rare and unworkable anyway).

So the real answer is: Why use unsigned in the first place?


Solution:5

On the second count: because they wanted the CLR to be compatible with languages that don't have unsigned datatypes (read: VB.NET).


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »