0

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.

Community
  • 1
  • 1
Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
  • I think you're looking for what's called a "saturated add". – Cameron Mar 21 '15 at 21:16
  • 1
    What you're looking for is called *saturation arithmetics*, and is afaik not available for built-in types and operators, because that would conflict with how programmers expect these to behave – Marcus Müller Mar 21 '15 at 21:16

1 Answers1

0

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;
}
Alex Sikilinda
  • 2,928
  • 18
  • 34
  • 1
    I'm aware to that. My question was if there is a built-in way for doing that. – Shimmy Weitzhandler Mar 21 '15 at 21:55
  • Isn't this built-in enough? – Patrick Hofman Mar 21 '15 at 22:15
  • 1
    @PatrickHofman For one, this construct is arguably much more verbose than e.g. `MyByteProperty = val > byte.MaxValue ? byte.MaxValue : val`, but even that you have to manually put around every assignment/calculation, as opposed to something built-in (which I believe does not exist). – GSerg Mar 21 '15 at 23:56