Why does C# issue the error “cannot implicitly convert int to ushort” against modulo arithmetic on ushorts?

前端 未结 2 1482
故里飘歌
故里飘歌 2021-01-18 09:12

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;  // E         


        
2条回答
  •  无人共我
    2021-01-18 09:29

    It's because the % operator is not defined for integer types smaller than int. The C# spec lists all overloads defined for the modulo operator on integer types:

    int operator %(int x, int y);
    uint operator %(uint x, uint y);
    long operator %(long x, long y);
    ulong operator %(ulong x, ulong y);
    

    https://github.com/dotnet/csharplang/blob/master/spec/expressions.md#remainder-operator

    Using %on ushorts then defaults to the first overload from the list above, which returns an int that can't be cast to ushort implicitly.


    If you ask why it's not defined, you probably would have to ask the creators of the C# specification.

提交回复
热议问题