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#?
<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .
%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.
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);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With