Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0036 string concatenation

C# reuses the + for string concatenation. using System; class Program { static void Main(string[] args) { string s1 = "abc"; string s2 = "rntsoft.com"; string s3 = s1 + s2; Console.WriteLine(s3); } } The output: abcrntsoft.com We can use the operator + to append other types to a string type. using System; class Program { static void Main(string[] args) { string s1 = "abc"; string s2 = s1 + 5; Console.WriteLine(s2); } } The output: abc5 Be careful when appending more than one variables to a string. using System; class Program { static void Main(string[] args) { string s1 = "abc"; string s2 = s1 + 5 + 5; Console.WriteLine(s2); } } The output: abc55 To get the result we want, we have to do the math first. using System; class Program { static void Main(string[] args) { string s1 = "abc"; string s2 = s1 + (5 + 5); Console.WriteLine(s2); } } The output: abc10