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

2020-02-06 01:55发布

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 - returns string

Chr(1) & Chr(2) = "  "

C# - returns int

(char)(1) + char(2) = 3

How can i add(concatenate) two chars in C#?

4条回答
Summer. ? 凉城
2楼-- · 2020-02-06 02:04

The best answer is in the comments so I want elevate it here to a proper answer. With full credit going to @Jeow Li Huan:

string res = string.Concat(charA, charB);
查看更多
手持菜刀,她持情操
3楼-- · 2020-02-06 02:07

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);
查看更多
疯言疯语
4楼-- · 2020-02-06 02:09

By adding to an empty string you can force the "conversion" of char to string... So

string res = "" + (char)65 + (char)66; // AB

(technically it isn't a conversion. The compiler knows that when you add to a string it has to do some magic... If you try adding null to a string, it consider the null to be an empty string, if you try adding a string it does a string.Concat and if you try adding anything else it does a .ToString() on the non-string member and then string.Concat)

查看更多
一夜七次
5楼-- · 2020-02-06 02:15

(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).

查看更多
登录 后发表回答