Reputation: 687
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#?
Upvotes: 9
Views: 17872
Reputation: 538
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);
Upvotes: 3
Reputation: 631
(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).
Upvotes: 0
Reputation: 111870
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
)
Upvotes: 5
Reputation: 726649
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);
Upvotes: 15