Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
341 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...