C# String Append

String type

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.

Example

Plus

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
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
Main method

Inside Main, a string reference is assigned the literal value "Dot Net ". Next, the word "Perls" is appended to the string with the += operator. This operator adds no integers. Instead it combines the two strings.

Finally:Another word is appended to the same string variable. And a new string object is created.

Example 2

Note

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 Examples
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

The Console.WriteLine method writes the string to your console window. It only adds a newline at the end of the output string, so the newline in between "One" and "Two" is from the string append.

Console.WriteLine

Internals

Framework: NET

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 content is useful for beginning developers or experienced developers who are changing languages.


C#: String