How to concatenate multiple strings - C# (2024)

  • Article

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.

Note

The C# examples in this article run in the Try.NET inline code runner and playground. Select the Run button to run an example in an interactive window. Once you execute the code, you can modify it and run the modified code by selecting Run again. The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

String literals

The following example splits a long string literal into smaller strings to improve readability in the source code. The code concatenates the smaller strings to create the long string literal. The parts are concatenated into a single string at compile time. There's no run-time performance cost regardless of the number of strings involved.

// 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.";System.Console.WriteLine(text);

+ and += operators

To concatenate string variables, you can use the + or += operators, string interpolation or the String.Format, String.Concat, String.Join or StringBuilder.Append 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 examples of using the + and += operators to concatenate strings:

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);

String interpolation

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

string userName = "<Type your name here>";string date = DateTime.Today.ToShortDateString();// Use string interpolation to concatenate strings.string str = $"Hello {userName}. Today is {date}.";System.Console.WriteLine(str);str = $"{str} How are you today?";System.Console.WriteLine(str);

Note

In string concatenation operations, the C# compiler treats a null string the same as an empty string.

Beginning with C# 10, you can use string interpolation to initialize a constant string when all the expressions used for placeholders are also constant strings.

String.Format

Another method to concatenate strings is String.Format. This method works well when you're building a string from a small number of component strings.

StringBuilder

In other cases, you may be combining strings in a loop where you don't know how many source strings you're combining, and the actual number of source strings may be large. The StringBuilder class was designed for these scenarios. The following code uses the Append method of the StringBuilder class to concatenate strings.

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

You can read more about the reasons to choose string concatenation or the StringBuilder class.

String.Concat or String.Join

Another option to join strings from a collection is to use String.Concat method. Use String.Join method if a delimiter should separate source strings. The following code combines an array of words using both methods:

string[] words = { "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog." };var unreadablePhrase = string.Concat(words);System.Console.WriteLine(unreadablePhrase);var readablePhrase = string.Join(" ", words);System.Console.WriteLine(readablePhrase);

LINQ and Enumerable.Aggregate

At last, you can use LINQand the Enumerable.Aggregate method to join strings from a collection. This method combinesthe source strings using a lambda expression. The lambda expression does thework to add each string to the existing accumulation. The following examplecombines an array of words, adding a space between each word in the array:

string[] words = { "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog." };var phrase = words.Aggregate((partialPhrase, word) =>$"{partialPhrase} {word}");System.Console.WriteLine(phrase);

This option can cause more allocations than other methods for concatenating collections, as it creates an intermediate string for each iteration. If optimizing performance is critical, consider the StringBuilder class or the String.Concat or String.Join method to concatenate a collection, instead of Enumerable.Aggregate.

See also

  • String
  • StringBuilder
  • Strings
How to concatenate multiple strings - C# (2024)
Top Articles
What is SSH and How Does it Work? | An Easy Explanation
Warts
Navicent Human Resources Phone Number
No Hard Feelings Showtimes Near Metropolitan Fiesta 5 Theatre
Uihc Family Medicine
COLA Takes Effect With Sept. 30 Benefit Payment
Nwi Police Blotter
Mlifeinsider Okta
Southland Goldendoodles
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Jcpenney At Home Associate Kiosk
Best Restaurants Ventnor
123Moviescloud
Top tips for getting around Buenos Aires
Blackwolf Run Pro Shop
All Obituaries | Buie's Funeral Home | Raeford NC funeral home and cremation
Cocaine Bear Showtimes Near Regal Opry Mills
The Pretty Kitty Tanglewood
Long Island Jobs Craigslist
Catherine Christiane Cruz
Babbychula
Betaalbaar naar The Big Apple: 9 x tips voor New York City
Knock At The Cabin Showtimes Near Alamo Drafthouse Raleigh
Drift Hunters - Play Unblocked Game Online
3569 Vineyard Ave NE, Grand Rapids, MI 49525 - MLS 24048144 - Coldwell Banker
Soul Eater Resonance Wavelength Tier List
New Stores Coming To Canton Ohio 2022
Riverstock Apartments Photos
Log in to your MyChart account
Salemhex ticket show3
How often should you visit your Barber?
R/Orangetheory
Devotion Showtimes Near The Grand 16 - Pier Park
140000 Kilometers To Miles
Newsday Brains Only
Green Bay Crime Reports Police Fire And Rescue
Craigslist Neworleans
No Hard Feelings Showtimes Near Tilton Square Theatre
Rocketpult Infinite Fuel
A Man Called Otto Showtimes Near Amc Muncie 12
Qlima© Petroleumofen Elektronischer Laserofen SRE 9046 TC mit 4,7 KW CO2 Wächter • EUR 425,95
Low Tide In Twilight Manga Chapter 53
Kenner And Stevens Funeral Home
Exam With A Social Studies Section Crossword
Levi Ackerman Tattoo Ideas
Craigslist Woodward
St Anthony Hospital Crown Point Visiting Hours
Bank Of America Appointments Near Me
Call2Recycle Sites At The Home Depot
211475039
Latest Posts
Article information

Author: Duane Harber

Last Updated:

Views: 6499

Rating: 4 / 5 (51 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Duane Harber

Birthday: 1999-10-17

Address: Apt. 404 9899 Magnolia Roads, Port Royceville, ID 78186

Phone: +186911129794335

Job: Human Hospitality Planner

Hobby: Listening to music, Orienteering, Knapping, Dance, Mountain biking, Fishing, Pottery

Introduction: My name is Duane Harber, I am a modern, clever, handsome, fair, agreeable, inexpensive, beautiful person who loves writing and wants to share my knowledge and understanding with you.