C# String - Concat() Method



The C# String Concat() method is used to concatenate or merge two or more strings into a single string. It supports concatenation of the arrays and other objects.

Syntax

Following are the syntax of the C# string Concat() method −

Basic Concatenation:

 public static string Concat(string? str1, string? str2); 

Concatenating Three Strings:

 public static string Concat(string? str1, string? str2, string? str3); 

Concatenating Multiple Strings:

 public static string Concat(params string?[] values); 

Concatenating Objects:

 public static string Concat(params object?[] args); 

Parameters

This method accepts more than one string, object, and array to concatenate.

Return value

This method returns a string, which is the concatenation of the multiple strings.

Example 1: Concatenate Two Strings

This is the basic example of the string Concat() method. Here, we concatenate two strings into a single string.

 using System; class Program { static void Main() { string str1 = "abcdef"; string str2 = "abcxyz"; // concatenate two strings string result = String.Concat(str1, str2); Console.WriteLine("concatenated: " + result); } } 

Output

Following is the output −

 concatenated: abcdefabcxyz 

Example 2: Concatenate Three Strings

Let us see another example of the Concat() method. Here, we use this method to concatenate three strings into a single string −

 using System; class Program { static void Main() { string str1 = "abcdef"; string str2 = " abcxyz"; string str3 = "Aman "; // concatenate three strings string result = String.Concat(str3, str1, str2); Console.WriteLine("concatenated: " + result); } } 

Output

Following is the output −

 

Example 3: Concatenate The Objects

In the following example, we use the Concat() method to concatenate more than two objects, all objects are different types. −

 using System; class Program { static void Main() { int number = 42; double pi = 3.14; string text = "The answer is "; string result = String.Concat(text, number, " and pi is approximately ", pi); Console.WriteLine(result); } } 

Output

Following is the output −

 The answer is 42 and pi is approximately 3.14 

Example 4: Concatenate an Array's elements

Here, in this example, we use another version of the Concat() method to concatenate the string array −

 using System; class Program { static void Main() { string[] words = { "This ", "is ", "a ", "tutorialspoint." }; string result = String.Concat(words); Console.WriteLine(result); } } 

Output

Following is the output −

 This is a tutorialspoint. 
csharp_strings.htm
Advertisements