Code

String Concatenation

Old way of string concatenation

A common use of string concatenation is to inject variable values into string using the string formatting syntax.

String.Concat( ) and “+”:
int a = 2;
int b = 5;

//+ operator concatenates two strings
string result = "Addition of " + a + " + " + b + " is " + (a + b);
//+ symbol actually translates to the String.Concat() method
string result = String.Concat("Addition of ", a, " + ", b, " is ", (a + b));
// OR
string result = string.Concat(new object[] {"Addition of ", a, " + ", b, " is ", (a + b)});
OUTPUT

Addition of 2 + 5 is 7

String.Join( ):
string result = String.Join(String.Empty, new object[] {"Addition of ", a, " + ", b, " is ", (a + b)});
// OR
string result1 = String.Join(String.Empty, "Addition of ", a, " + ", b, " is ", (a + b));
String.Format( ):

String Concatenation

String Interpolation

int a = 2;
int b = 5;

string result = $"Addition of {a} + {b} is {a + b}"; // string interpolation

which translates to

string result = String.Format("Addition of {0} + {1} is {2}", a, b, (a+b));
OUTPUT

Addition of 2 + 5 is 7

decimal saving = 786.78m;
Console.WriteLine($"My saving this month is {saving:C}.");
OUTPUT

My saving this month is $786.78.

Run Demo

Pirzada Rashid

Senior .NET developer with a Master of Science in Information Technology.
Teaching is one of my passions. It gives me great joy to share my knowledge with others, and I look forward to investing more energy into it.

Add Comment

Click here to post a comment

Popular Video

82,490+ Views