Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

char

vb.net

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#?

like image 358
SarkarG Avatar asked Aug 20 '13 12:08

SarkarG


People also ask

What does << mean in C?

<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .

What does %d do in C?

%d is a format specifier, used in C Language. Now a format specifier is indicated by a % (percentage symbol) before the letter describing it. In simple words, a format specifier tells us the type of data to store and print. Now, %d represents the signed decimal integer.


2 Answers

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);
like image 191
Sergey Kalinichenko Avatar answered Oct 24 '22 07:10

Sergey Kalinichenko


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)

like image 32
xanatos Avatar answered Oct 24 '22 08:10

xanatos