Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference of two 'uint'

Tags:

c#

.net

When you attempt to declare an unsigned variable in C#.NET with a value outside its value range it is flagged as a compiler error, but if you produce a negative value at runtime and assign it to that variable at runtime the value wraps.

uint z = -1; // Will not compile

uint a = 5;
uint b = 6;
uint c = a - b; // Will result in uint.MaxValue

Is there a good reason why unsigned variables wrap in such a situation instead of throwing an exception?

Thanks.

like image 454
Llyle Avatar asked Oct 26 '08 21:10

Llyle


1 Answers

Declaring an unassigned variable in C# isn't flagged with an error - trying to assign an invalid value to a variable is. For instance, here's a variable which isn't definitely assigned (assuming it's local) after declaration:

uint z;

-1 isn't a valid value for a uint any more than 0.5 is, which is why your example wouldn't compile.

Now, as for the rest: integers types just wrap on overflow - just as adding 1 to int.MaxValue returns int.MinValue. This is a significant performance improvement over having the program check each operation for overflow - at the cost of potentially not spotting an error.

That's only if you're in an unchecked context, mind you - if you perform any of these operations in a checked context, you'll get an exception instead. For instance;

class Test
{
    static void Main()
    {
        checked
        {
            uint a = 5;
            uint b = 6;
            uint c = a - b;
        }
    }
}

Run that and you'll see an OverflowException get thrown. If that's what you want for your whole project, you can set it in the project properties (or compile with the /checked+ command line option to csc.)

EDIT: It's worth noting that the other answers have shown that you could put smaller amounts of code in the checked context - just the declaration and assignment of c or even just the calculation. It's all pretty flexible.

like image 103
Jon Skeet Avatar answered Oct 07 '22 02:10

Jon Skeet