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

前端 未结 2 1508
故里飘歌
故里飘歌 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:34

    The % operator that's being used, even with shorts or ushorts, has a signature of int %(int a, int b). So your shorts are being lifted up into integers, and your result is an integer you are attempting to assign to a ushort, which is a lossy cast so you are required to be explicit.

    Consider this:

    ushort x = 5;
    ushort y = 6;
    var res = x % y;
    Console.WriteLine(res.GetType()); // System.Int32
    ushort z = res; // cast error, explicit conversion exists
    ushort zz = (ushort)res; // Fine, we cast down.
    

提交回复
热议问题