Search code examples
c#integer-overflowarithmetic-expressionsinteger-arithmeticoverflowexception

Get max value on arithmethic overflow


Is there a built-in way to get max value on arithmetic overflow?

Here's what I need:

var val = byte.MaxValue + 1;

//should be rounded down to byte.MaxValue
MyByteProperty = val;

P.S. I know I can do that by wrapping it as a checked expression as Alex answered, my question is if there's a built-in way in the language or BCL.


Solution

  • There are checked and unchecked keywords, that indicate whether exception will be thrown if overflow occures:

    try
    {
        MyByteProperty = checked(byte.MaxValue + 1);
    }
    catch (System.OverflowException e)
    {
        MyByteProperty = byte.MaxValue;
    }