From what I've noticed in C# when a byte
has its max value (255) then adding a value, for example 10, you get a byte with value of 9.
byte number = byte.MaxValue;
number += 10;
Console.WriteLine(number.ToString()); // prints 9
To get around that problem I wrote the Add
extention method.
static void Add(this byte b, byte value)
{
int result = b + value;
if (result.IsInByteRange())
{
b = (byte)result;
Console.WriteLine(b.ToString());
}
else
{
b = byte.MaxValue;
}
}
static bool IsInByteRange(this int i)
{
var largerEqualsMin = i >= byte.MinValue;
var lesserEqualsMax = i <= byte.MaxValue;
return largerEqualsMin && lesserEqualsMax;
}
While debugging I can see that the b
inside Add()
is the prefered value but if I execute the bellow:
byte number = 0;
number.Add(10);
Console.WriteLine("Calling from Main() "+ number.ToString());
The output is:
Calling from Add() 10
Calling from Main() 0
Why at the end the result is zero?