Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
971 views
in Technique[技术] by (71.8m points)

.net - C# Overflow not Working? How to enable Overflow Checking?

I was working around with C# and noticed that when I had a very large integer and attempted to make it larger. Rather that throwing some type of overflow error, it simply set the number to the lowest possible value (-2,147,483,648) I believe.

I was wondering if there was a way to enable the overflow checking in Visual Studio?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the following steps to enable Arithmetic Overflow/Underflow checking in Visual Studio :

  1. Right click on your project in the Solution Explorer and select Properties.
  2. On the Build tab, click the Advanced button. (It's towards the bottom)
  3. Check the "Check for arithmetic overflow / underflow" check-box.

This will throw a System.OverflowException when the overflow occurs rather than it's usual operation of changing the value to a minimum value.

Without Arithmetic Overflow/Underflow enabled:

int test = int.MaxValue;
test++;
//Test should now be equal to -2,147,483,648 (int.MinValue)

With Arithmetic Overflow/Underflow enabled:

int test = int.MaxValue;
test++;
//System.OverflowException thrown

Using a checked block:

checked
{
    int test = int.MaxValue;
    test++;
    //System.OverflowException thrown
}

The documentation for checked is available here. (Thanks to Sasha for reminding me about it.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...