Integer summing blues, short += short problem

后端 未结 5 767
野趣味
野趣味 2020-11-22 10:42

Program in C#:

short a, b;
a = 10;
b = 10;
a = a + b; // Error : Cannot implicitly convert type \'int\' to \'short\'.

// we can also write this code by usin         


        
5条回答
  •  清酒与你
    2020-11-22 11:26

    You have to use:

    a = (short)(a + b);
    

    As to the difference between the behaviours of assignment and addition assignment, I imagine it has something to do with this (from msdn)

    x+=y
    is equivalent to
    x = x + y
    except that x is only evaluated once. The meaning of the + operator is
    dependent on the types of x and y (addition for numeric operands, 
    concatenation for string operands, and so forth).
    

    However, it's a bit vague, so mabye someone with a deeper understanding can comment.

提交回复
热议问题