HomeSearch

C# String Append (Add Strings)

Add strings together, appending them, with the plus operator.
String append. Strings can be appended one after another. There is no actual Append method on the string type. We provide a quick reference for how to add one string on the end to an existing string.Strings
Example. Many programmers are familiar with appending strings, but the string type lacks an "Append" method. Instead, it is best to use the plus operator on different instances of strings.

Next: The example shows how to append string references and literals. It displays the output of the console program.

String Literal

Main: A string reference is assigned the literal value "Dot Net ". The word "Perls" is appended to the string with the += operator.

Info: This operator adds no integers. Instead it combines the two strings. Another word is appended to the same string variable.

C# program that appends strings using System; class Program { static void Main() { // // This is your input string. // string value = "Dot Net "; // // Append the word "Perls" to the string. // value += "Perls"; // // Write the string to the screen. // Console.WriteLine(value); // // Append this word to the string. // value += " Basket"; // // Write the new string. // Console.WriteLine(value); } } Output Dot Net Perls Dot Net Perls Basket
Example 2. Let's look at how you can append string values—and append multiple values at once. This example creates a two-line string, using three string variables. We also see the Environment.NewLine property.Environment.NewLineProperty

Console: The Console.WriteLine method writes the string to your console window. It adds a newline at the end of the output string.

Console
C# program that appends line to string using System; class Program { static void Main() { // // Your input string. // string value1 = "One"; // // Another input string. // string value2 = "Two"; // // Append newline to string and also string. // value1 += Environment.NewLine + value2; // // Write output to the console. // Console.WriteLine(value1); } } Output One Two
Internals. When you compile one of the above C# programs, the compiler will transform the + operators into calls to String.Concat. You can actually use String.Concat instead of the code here for the same effect.string.Concat

However: It is fine to think of this code as string appending, because the end result is the same, regardless of implementation.

Summary. We looked at how you can append strings in the C# language. It is easiest to use the + operator for quick programs. This is useful for beginning developers or experienced developers who are changing languages.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls