Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 724
Earlz Avatar asked Jul 15 '10 20:07

Earlz


3 Answers

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.)

like image 139
Jon Skeet Avatar answered Sep 27 '22 19:09

Jon Skeet


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.

like image 40
Jess Avatar answered Sep 27 '22 19:09

Jess


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.

like image 43
Mike M. Avatar answered Sep 27 '22 19:09

Mike M.