views:

47

answers:

1

Has anyone found it strange that the default context for uint and ulong is unchecked rather than checked considering that they are meant to represent values that can never be negative?

So if some code is trying to violate that constraint it seems to me the natural and preferred behaviour would be to throw an exception rather than returning the max value instead (which can easily leave important pieces of data in an invalid state and impossible to revert..).

Is there an existing attribute which can be applied to either class/assembly so that it always performs arithmetic operations in a checked context? I was thinking of writing one myself (as an aspect using PostSharp) but would be great if there's one already.

Many thanks,

+2  A: 

I don't see what's different about unsigned integers here compared with signed ones... why is underflowing from 0 to uint.MaxValue likely to be better than underflowing from int.MinValue to int.MaxValue?

If you want a whole assembly to be compiled with checking, just use /checked (or /checked+ to be more explicit) on the command line or in Visual Studio, under the project properties find the Build tab, click "Advanced..." and tick the "Check for arithmetic overflow/underflow" box.

I don't believe there's any way to do this just for a particular class.

Jon Skeet
totally agree with your point on signed integers, this default behaviour of handling underflowing seems strange, do you know why it was designed this way? and thanks for the tip on making the whole assembly to be compiled with checking, it's precisely what I'm after! :-)
theburningmonk
@theburningmonk: I believe the default was chosen because it performs significantly better than the checked implementation. It's worth noting that you probably want unchecked blocks for calculating hash codes, where it's really just the bit pattern that matters, not the magnitude.
Jon Skeet