In another thread, someone asked about why adding two ushort
values raised errors in C#. e.g.
ushort x = 4;
ushort y = 23;
ushort z = x+y; // ERROR cannot implicitly convert int to ushort
On that thread, people argued that the plus + operater takes two ints by default, and this is a language feature to help avoid arithmetic overflows. But I get the same kind of error in the following function:
public RGB(ushort red, ushort green, ushort blue)
{
// this class RGB has three ushort fields: r, g, and b
r = red % ((ushort)256);
g = green % ((ushort)256);
b = blue % ((ushort)256);
}
where the compiler errors and says "Cannot implicitly convert type 'int' to 'ushort'. An explicit conversion exists...". But here the argument that the modulo % operator is guarding against overflow doesn't make any sense at all: if x and y are ushort
values, then x%y < max(x,y)
, so there is no risk of overflowing into ints. So why am I getting this error?