Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .openpublishing.redirection.json
Original file line number Diff line number Diff line change
Expand Up @@ -1079,6 +1079,10 @@
{
"source_path": "docs/csharp/programming-guide/strings/how-to-parse-strings-using-string-split.md",
"redirect_url": "docs/csharp/how-to/parse-strings-using-string-split.md"
},
{
"source_path": "docs/csharp/programming-guide/strings/how-to-concatenate-multiple-strings.md",
"redirect_url": "/dotnet/csharp/how-to/how-to-concatenate-multiple-strings.md"
}
]
}
60 changes: 60 additions & 0 deletions docs/csharp/how-to/concatenate-multiple-strings.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
---
title: "How to: Concatenate Multiple Strings (C# Guide)"
description: There are multiple ways to concatenate strings in C#. Learn the options and the reasons behind different choices.
ms.date: 01/11/2018
ms.prod: .net
ms.technology:
- "devlang-csharp"
ms.topic: "article"
helpviewer_keywords:
- "joining strings [C#]"
- "concatenating strings [C#]"
- "strings [C#], concatenation"
ms.assetid: 8e16736f-4096-4f3f-be0f-9d4c3ff63520
caps.latest.revision: 21
author: "BillWagner"
ms.author: "wiwagn"
---
# How to: Concatenate Multiple Strings (C# Guide)

*Concatenation* is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

The following example uses concatenation to split a long string literal into smaller strings in order to improve readability in the source code. These parts will be concatenated into a single string at compile time. There is no run-time performance cost regardless of the number of strings involved.

[!code-csharp-interactive[Combining strings at compile time](../../../samples/snippets/csharp/how-to/strings/Concatenate.cs#1)]


To concatenate string variables, you can use the `+` or `+=` operators, [string interpolation](../tutorials/string-interpolation.md) or the <xref:System.String.Concat%2A?displayProperty=nameWithType>, <xref:System.String.Format%2A?displayProperty=nameWithType> or <xref:System.Text.StringBuilder.Append%2A?displayProperty=nameWithType> methods. The `+` operator is easy to use and makes for intuitive code. Even if you use several + operators in one statement, the string content is copied only once. The following code shows two examples of using the `+` operator to concatenate
strings:

[!code-csharp-interactive[combining strings using +](../../../samples/snippets/csharp/how-to/strings/Concatenate.cs#2)]

In some expressions, it is easier to concatenate strings using string interpolation, as the following code shows:

[!code-csharp-interactive[building strings using string interpolation](../../../samples/snippets/csharp/how-to/strings/Concatenate.cs#3)]

> [!NOTE]
> In string concatenation operations, the C# compiler treats a null string the same as an empty string.

Other methods to concatenate strings are <xref:System.String.Concat%2A?displayProperty=nameWithType> and <xref:System.String.Format%2A?displayProperty=nameWithType>. These methods work well when you are building a string from a small number of component strings. These methdos are also a great choice when you know the number of strings that make up your concatenated string.

In other cases you may be combining strings in a loop, where you don't know how many source strings you are combining, and the actual number of source strings may be quite large. The <xref:System.Text.StringBuilder> class was designed for these scenarios. The following code uses the <xref:System.Text.StringBuilder.Append%2A> method of the <xref:System.Text.StringBuilder> class to concatenate strings.

[!code-csharp-interactive[string concatenation using string builder](../../../samples/snippets/csharp/how-to/strings/Concatenate.cs#4)]

You can read more about the [reasons to choose string concatenation or the `StringBuilder` class](xref:System.Text.StringBuilder#stringAndSB)

Another option to join strings from a collection is to use [LINQ](../programming-guide/concepts/linq/index.md)
and the <xref:System.Linq.Enumerable.Aggregate%2A?displayProperty=nameWithType> method. This method combines
the source strings using a lambda expression. The lambda expression does the
work to add each string to the existing accumulation. The following example
combines an array of words by adding a space between each word in the array:

[!code-csharp-interactive[string concatenation using LINQ expressions](../../../samples/snippets/csharp/how-to/strings/Concatenate.cs#5)]


## See Also
<xref:System.String>
<xref:System.Text.StringBuilder>
[C# Programming Guide](../programming-guide/index.md)
[Strings](../programming-guide/strings/index.md)
2 changes: 1 addition & 1 deletion docs/csharp/how-to/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ Strings are the fundamental data type used to display or manipulate text. These
- [Modify the contents of a string](../programming-guide/strings/how-to-modify-string-contents.md).
- [Determine if a string represents a number](../programming-guide/strings/how-to-determine-whether-a-string-represents-a-numeric-value.md).
- [Use `String.Split` to separate strings](parse-strings-using-split.md).
- [Combine multiple strings into one](../programming-guide/strings/how-to-concatenate-multiple-strings.md).
- [Combine multiple strings into one](sconcatenate-multiple-strings.md).
- [Search for text in a string](../programming-guide/strings/how-to-search-strings-using-string-methods.md).
- [Search strings using regular expressions](../programming-guide/strings/how-to-search-strings-using-regular-expressions.md).

Expand Down

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

1 change: 1 addition & 0 deletions docs/toc.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@
### [Versioning](csharp/versioning.md)
## [How To C# Topics](csharp/how-to/index.md)
### [How to parse strings using `String.Split`](csharp/how-to/parse-strings-using-split.md)
### [How to concatenate strings](csharp/how-to/concatenate-multiple-strings.md)
<!-- End of C# Concepts section -->
## [The .NET Compiler Platform SDK (Roslyn APIs)](csharp/roslyn-sdk/)
## [C# Programming Guide](csharp/programming-guide/)
Expand Down
90 changes: 90 additions & 0 deletions samples/snippets/csharp/how-to/strings/Concatenate.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;

namespace HowToStrings
{
static public class Concatenate
{
public static void Examples()
{
UsingAddWithConstantStrings();
UsingAddWithVariables();
UsingInterpolationWithVariables();
UsingStringBuilder();
UsingAggregate();
}

private static void UsingAddWithConstantStrings()
{
// <Snippet1>
// Concatenation of literals is performed at compile time, not run time.
string text = "Historically, the world of data and the world of objects " +
"have not been well integrated. Programmers work in C# or Visual Basic " +
"and also in SQL or XQuery. On the one side are concepts such as classes, " +
"objects, fields, inheritance, and .NET Framework APIs. On the other side " +
"are tables, columns, rows, nodes, and separate languages for dealing with " +
"them. Data types often require translation between the two worlds; there are " +
"different standard functions. Because the object world has no notion of query, a " +
"query can only be represented as a string without compile-time type checking or " +
"IntelliSense support in the IDE. Transferring data from SQL tables or XML trees to " +
"objects in memory is often tedious and error-prone.";

Console.WriteLine(text);
// </Snippet1>
}

private static void UsingAddWithVariables()
{
// <Snippet2>
string userName = "<Type your name here>";
string dateString = DateTime.Today.ToShortDateString();

// Use the + and += operators for one-time concatenations.
string str = "Hello " + userName + ". Today is " + dateString + ".";
System.Console.WriteLine(str);

str += " How are you today?";
System.Console.WriteLine(str);
// </Snippet2>
}
private static void UsingInterpolationWithVariables()
{
// <Snippet3>
string userName = "<Type your name here>";
string date = DateTime.Today.ToShortDateString();

// Use the + and += operators for one-time concatenations.
string str = $"Hello {userName}. Today is {date}.";
System.Console.WriteLine(str);

str = $"{str} How are you today?";
System.Console.WriteLine(str);
// </Snippet3>
}

private static void UsingStringBuilder()
{
// <Snippet4>
// Use StringBuilder for concatenation in tight loops.
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < 20; i++)
{
sb.AppendLine(i.ToString());
}
System.Console.WriteLine(sb.ToString());
// </Snippet4>
}

private static void UsingAggregate()
{
// <Snippet5>
string[] words = { "The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog." };

var phrase = words.Aggregate((partialPhrase, word) =>$"{partialPhrase} {word}");
Console.WriteLine(phrase);
// </Snippet5>
}
}
}
1 change: 1 addition & 0 deletions samples/snippets/csharp/how-to/strings/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ class Program
static void Main(string[] args)
{
ParseStringsUsingSplit.Examples();
Concatenate.Examples();
}
}
}
1 change: 1 addition & 0 deletions samples/snippets/csharp/how-to/strings/strings.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
<RootNamespace>HowToStrings</RootNamespace>
</PropertyGroup>

</Project>