6 Effective Ways To Concatenate Strings In C# and .NET Core

6 Effective Ways To Concatenate Strings In C# and .NET Core
 
Concatenating string is appending or inserting one string to the end of another string. Strings in C# and .NET Core are immutable. That means, even if you use same string variable, after every operation, a new string object is created.
 
Adding strings is a common operation in C# and .NET. The String class provides several ways to add, insert, and merge strings including + operator, String.Concate(), String.Join(), String.Format(), StringBuilder.Append(), and String Interpolation. The code examples demonstrate various methods to concatenate strings, insert string, append string, and merge strings using C# String class and its methods.
 
C# String concatenation  
 
Here are the 6 ways to concatenate strings in C#. 
  1. Using + operator
  2. String Interpolation
  3. String.Concatenate() method
  4. String.Join() method
  5. String.Format() method
  6. StringBuilder.Append() method
 

1. Concatenate String Using + Operator

 
The simplest method of adding two strings in C# is using + or += operators.
 
The following code example in Listing 1 concatenates two strings and a special character. 
  1. // Simple string concatenation   
  2. Console.WriteLine("Hello" + " " + "String " + "!");  
The following code example concatenates two string variables. 
  1. // Declare strings  
  2. string firstName = "Mahesh";  
  3. string lastName = "Chand";  
  4.   
  5. // Concatenate two string variables  
  6. string name = firstName + " " + lastName;  
  7. Console.WriteLine(name);  
Listing 1.
 
Result of Listing 1 is displayed in Figure 1.
 
 
 
Figure 1.
 
Note: For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.
 

2. String Interpolation

 
String interpolation is a method to concatenate variables as a part of a string. Syntax of string interpolation starts with a ‘$’ symbol and code variables are within a bracket {}.
 
The following code example in Listing 2 concatenates strings to create a longer string. 
  1. // String Interpolation  
  2. string author = "Mahesh Chand";  
  3. string book = "C# Programming";  
  4. // Use string interpolation to concatenate strings.  
  5. string bookAuthor = $"{author} is the author of {book}.";  
  6. Console.WriteLine(bookAuthor);  
Listing 2.

3. Concatenate string using String.Concate method

 
String.Concate() method concatenates two strings, two objects, and two arrays of strings and combinations of them.
 
The following code example in Listing 3 concats two strings. 
  1. // String.Concat method  
  2. string fName = "Mahesh";  
  3. string lName = "Chand";  
  4. string Name = string.Concat(fName, lName);  
Listing 3.
 
The following code example in Listing 4 concats a Concat inside a Concat. 
  1. // Concatenate Concat  
  2. string Name3 = string.Concat(string.Concat(fName, lName), "Beniwal");  
Listing 4.
 
The following code example in Listing 5 concats four strings into a single string. 
  1. // Concatenate an array of strings  
  2. string[] authors = { "Mahesh Chand ""Chris Love ""Dave McCarter ""Praveen Kumar "};  
  3.   
  4. // Concatenate all strings of an array into one string  
  5. string arrayStr = string.Concat(authors);  
  6. Console.WriteLine(arrayStr);  
Listing 5.
 
The following code example in Listing 6 concats a string with an array of strings into a single string. 
  1. // Concatenate a string and an array of strings  
  2. string strArrStr = string.Concat("Authors: ", authors);  
  3. Console.WriteLine(strArrStr);  
Listing 6.
 

4. Concatenate string using String.Join method

 
String.Join() method concatenates the elements of an array or the members of a collection, using the specified separator between each element or member. The array or the collection can be any data type including numbers and objects. String.Join method also allows you to concatenate string items of any data types with a range.
 
The following code example in Listing 7 concatenates an array of int values to a string separated by a comma and space. 
  1. // Using String.Join(String, String[])  
  2. int[] intArray = { 1, 3, 5, 7, 9 };  
  3. String seperator = ", ";  
  4. string result = "Int, ";  
  5. result += String.Join(seperator, intArray);  
  6. Console.WriteLine($"Result: {result}");  
Listing 7.
 
The following code example in Listing 8 concatenates an array element separated by a separator. The second and third parameters of String.Join method specified the starting index of the array to start joining the number of elements in the array.
  1. // Using String.Join(String, String[], int int)  
  2. // Let's concatenate first two strings of the array  
  3. String[] arr2 = { "Mahesh Chand ""Chris Love ""Dave McCarter ""Praveen Kumar " };  
  4. String seperator2 = ", ";  
  5. string result2 = "First Author, ";  
  6. result2 += String.Join(seperator2, arr2, 1, 2);  
  7. Console.WriteLine($"Result: {result2}");  
Listing 8.

5. Concatenate string using String.Format method

 
String.Format() method formats strings in a desired format by inserting objects and variables with specified space and alignments into another strings and literals. It is also often used to format strings into specific formats.
 
String.Format() method has 8 overloaded formats to provide options to format various objects and variables that allow various variables to format strings.
 
Note: In C# 6 or later versions, String Interpolation is recommended. Sting interpolation is more flexible and more readable and can achieve the same results without composite formatting.
 
Insert a single object in a string
 
We can insert one or more objects and expressions in a string at a specified position using the String.Format method. The position in the string starts at the 0th index.
 
For single object formatting, the first argument is the format and the second argument is the value of the object. The object is replaced at the {0} position in the string. 
  1. public static string Format (string format, object arg0);  
The following code example in Listing 9 inserts a DateTime object in an existing string format. 
  1. /* *** Simple String.Format **/  
  2. string date = String.Format("Today's date is {0}", DateTime.Now);  
  3. Console.WriteLine(date);  
Listing 9.
 
As you can see from the above code example, {0} is at the last portion in the string and the second argument is a DateTime.Now. In this case, string portion {0} will be replaced by the value of DateTime.Now in the string. Figure 2 is the result of the above code.
 
Insert string object in C# 
 
Figure 2.
 
Insert multiple objects in a string
 
We can insert multiple objects or expressions in a string to give it a desired format. The following code example in Listing 10 creates a string by inserting 5 objects. 
  1. /* *** String.Format with multiple objects **/  
  2. string author = "Mahesh Chand";  
  3. string book = "Graphics Programming with GDI+";  
  4. int year = 2003;  
  5. decimal price = 49.95m;  
  6. string publisher = "APress";  
  7.   
  8. // Book details  
  9. string bookDetails = String.Format("{0} is the author of book {1} \n " +  
  10. "published by {2} in year {3}. \n Book price is ${4}. ",  
  11. author, book, publisher, year, price);  
  12. Console.WriteLine(bookDetails);  
Listing 10.
 
As you can see from the above code example, the String.Format has placeholders for objects, starting at 0th to 4th index. The {0} is replaced by the first object passed in the method, {1} is replaced by the second object passed in the method and so on.
 
The output of Listing 10 generates Figure 3.
 
Insert multiple string object in C# 
 
Figure 3.
 

6. StringBuilder.Append method

 
String object in .NET is immutable. What does that mean? It means every time you use one of the String class methods, no matter if you use the same variable or a new variable, a new string object is created in memory. That means, a memory space is allocated for that new string in your computer memory. The more string methods you use to manipulate strings, the more memory space will be allocated in memory. That means in a string manipulation heavy code, if strings are not used wisely, it could lead to some serious app performance issues.
 
.NET provides the System.Text.StringBuilder class that can be used to modify strings without creating new string objects. StringBuilder is highly recommended if you have more than a few hundred string concatenation operations in your code. StringBuilder is not recommended for a few string concatenation operations.
 
StringBuilder class is defined in the System.Text namespace. You must either import this namespace in your class or reference is direct in the object instantiation. 
  1. using System.Text;  
StringBuilder constructor can take a string or can be no arguments.
 
The following code snippet creates a StringBuilder and appends 3 strings. 
  1. System.Text.StringBuilder builder = new System.Text.StringBuilder("Mahesh Chand");  
  2. builder.Append(", ");  
  3. builder.Append("Chris Love");  
  4. builder.Append(", Praveen Kumar");  
  5.    
The following code example creates a string of numbers from 0 to 999 and each number is separated by a comma and a space. 
  1. System.Text.StringBuilder numbers = new System.Text.StringBuilder();  
  2. // Create a string of 1000 numbers from 0 to 999  
  3. // separated by a comma and space  
  4. for (int counter = 0; counter <= 999; counter++)  
  5. {  
  6. numbers.Append(counter);  
  7. numbers.Append(", ");  
  8. }  
  9. Console.WriteLine(numbers);  
  10.    
The output of the above code looks like Figure 4.
 
StringBuilder.Append() 
 
Figure 4.
 

Summary

 
C# and .NET provide various options to concatenate strings. In the code examples listed in this article, we saw how to use these options to concatenate strings.