C# String Concat() Method
The Concat()
method in C# is a static method of the String
class that is used to concatenate two or more strings. It returns a new string that contains the concatenated strings.
Here is an example of using the Concat()
method:
string str1 = "Hello, "; string str2 = "world!"; string result = String.Concat(str1, str2); Console.WriteLine(result); // Output: Hello, world!
In this example, we concatenate the strings "Hello, " and "world!" using the Concat()
method, and store the result in the result
variable. The Console.WriteLine()
statement then prints the concatenated string to the console.
The Concat()
method has overloads that allow you to concatenate multiple strings at once, as well as objects of other types, such as integers or floats. Here is an example of concatenating multiple strings using the Concat()
method:
string str1 = "one"; string str2 = "two"; string str3 = "three"; string str4 = "four"; string result = String.Concat(str1, str2, str3, str4); Console.WriteLine(result); // Output: onetwothreefour
In this example, we concatenate the four strings "one", "two", "three", and "four" using the Concat()
method.
Note that if you only need to concatenate a small number of strings, you can use the +
operator instead of the Concat()
method. However, the Concat()
method is more efficient for concatenating large numbers of strings, since it avoids creating intermediate strings.