Home
C#
String Append (Add Strings)
Updated Nov 2, 2023
Dot Net Perls
String append. Strings can be appended one after another. There are no Append or Add methods on the string type. And strings must be copied, not modified in-place.
Notes, appending. We provide a quick reference for how to add one string on the end to an existing string. The concat operator can be used.
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.
Step 1 A string reference is assigned the literal value "cat." The word "and" is appended to the string with the "+=" operator.
String Literal
Step 2 We append another word to the string. A new string is created, and the identifier "value" now points to it.
using System; string value = "cat "; // Step 1: append a word to the string. value += "and "; Console.WriteLine(value); // Step 2: append another word. value += "dog"; Console.WriteLine(value);
cat and cat and dog
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 3 string variables.
Also We see the Environment.NewLine property. This represents the newline sequence, which is 2 chars.
Environment.NewLine
Property
using System; string value1 = "One"; string value2 = "Two"; // Append newline to string and also string. value1 += Environment.NewLine + value2; Console.WriteLine(value1);
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 use String.Concat 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. It is easiest to use the + operator. And we can append to an existing variable with the += operator.
StringBuilder
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 2, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen