views:

177

answers:

4

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.

+15  A: 

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

Jon Skeet
"although I could be wrong" - You mean .NET could have been wrong?
PostMan
@PostMan: I've just found a bit more information... will edit.
Jon Skeet
+1  A: 

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.

Mike M.
Can someone with enough reputation to edit correct that to say "unsigned integer of 3B into a signed integer?" His intention was clear, just a typo.
Dave McClelland
Thanks Dave, I even re-read it and missed it :x
Mike M.
+3  A: 

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.

Andrew Koester
A: 

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

Seva Alekseyev
VB.net has had unsigned numbers since at least 2.0. I wasn't aware of them being missing earlier, but that would make a lot of sense -- they weren't in VB in time to make it into the CLS.
cHao
But changing the String class in .NET v2 (or, for that matter, ever) would break a huge amount of code.
Seva Alekseyev