Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C# throw casting errors when attempting math operations on integer types other than int?

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 image 454
Robert Harvey Avatar asked Jul 21 '10 17:07

Robert Harvey


1 Answers

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 ints than on shorts 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.

like image 174
Stephen Cleary Avatar answered Sep 30 '22 14:09

Stephen Cleary