I noticed that when Byte plus Byte, it will produce int, Is it possible to let byte a +byte b and produce 255 if it overflows?
Byte a=200;
Byte b=200
Byte output = (a+b); // now output equals 144, I want 255
How about this (untested)?
byte output = (byte)(Math.Min(a + b, Byte.MaxValue));
byte.MaxValue is a bit more readable than magic constant 255This usually happens when a number overflows which is not in a checked statement.
If you want it to produce 255 then the most simple option I can think of would be to use a ternary operation:
byte output = (int)a + (int)b > byte.MaxValue ? byte.MaxValue : a + b;
The other option I can think of would be to create your own data type that handles this for you.
This will throw OverflowException:
checked
{
Byte a=200;
Byte b=200
Byte output = (a+b);
}
And this way you can catch and process it:
Byte output;
try
{
checked
{
Byte a=200;
Byte b=200
output = (a+b);
}
}
catch(OverflowException e)
{
output = Byte.MaxValue;
}
Console.WriteLine(output);
But I suggest you to control your flow yourself. Catching exceptions is bad approach, but if you have complex calculation, it can be troublesome. Just use Math instead:
var output = (Byte)Math.Min((int)a+b, Byte.MaxValue);
output - adoesn't equalbanymore!