Consider this static test class:
public static class Test
{
public static ushort sum(ushort value1, ushort value2)
{
return value1 + value2
}
}
This causes the following compile error, with value1 + value2
underlined in red:
Cannot implicitly convert type 'int' to 'ushort'. An explicit conversion exists (are you missing a cast)?
Why?
Like C and C++ before it, integers are implicitly widened when used with many operators. In this case, the result of adding two ushort
values together is int
.
Update:
More information: http://msdn.microsoft.com/en-us/library/aa691330(v=VS.71).aspx
I believe this was originally added in C/C++ because int
was a native integer type (and yes, operations were faster on int
s than on short
s on 32-bit architectures). I'm unsure of the full rationale for C#.
It does make you think about overflow/truncation considerations when you cast. Accidental overflow is more likely with the smaller integer types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With