开发者

Making sure unsigned int/long always execute in checked context in C#

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 开发者_如何学JAVAarithmetic 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,


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜