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

前端 未结 4 1484
梦毁少年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:39

    In C# char is a 16-bit numeric type, so + means addition, not concatenation. Therefore, when you add a and b you get a+b. Moreover, the result of this addition is an int (see a quick demo).

    If by "adding two characters" you mean "concatenation", converting them to a strings before applying operator + would be one option. Another option would be using string.Format, like this:

    string res = string.Format("{0}{1}", charA, charB);
    

提交回复
热议问题