In c# why (char)(1) + (char)(2) results in int 3

前端 未结 4 1480
梦毁少年i
梦毁少年i 2020-12-10 15:53

I am trying to covert some VB.NET code to C# and found this interesting thing. Adding two chars returns different results in VB.NET and C#.

VB.NET -

4条回答
  •  暖寄归人
    2020-12-10 16:49

    (char)(1) has an ascii value of 1 and (char)(2) ascii value of 2

    so ascii value of 1 + 2 (i.e. (char)1 + (char)2 ) will be equal to 3.

    if you do: "2" + "1" this will give you "21" (althou you should not use this to join strings, bad practice)

    if you do: '2' + '1' this will give you int value of 99 that is ascii value of 2 (which is 50) + ascii value of 1(which is 49).

提交回复
热议问题