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