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#?
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:
In C#
char
is a 16-bit numeric type, so+
means addition, not concatenation. Therefore, when you adda
andb
you geta+b
. Moreover, the result of this addition is anint
(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 usingstring.Format
, like this:By adding to an empty string you can force the "conversion" of
char
tostring
... So(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 addingnull
to a string, it consider thenull
to be an empty string, if you try adding astring
it does astring.Concat
and if you try adding anything else it does a.ToString()
on the non-string member and thenstring.Concat
)(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).