Pergunta

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,

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top