0
0
C Sharp (C#)programming~15 mins

String concatenation behavior in C Sharp (C#) - Deep Dive

Choose your learning style9 modes available
Overview - String concatenation behavior
What is it?
String concatenation is the process of joining two or more strings together to form a new string. In C#, this can be done using the + operator or special classes like StringBuilder. It allows you to combine words, sentences, or any text data into one continuous string. This is a common task when working with text in programs.
Why it matters
Without string concatenation, it would be very hard to build dynamic messages, create formatted output, or combine user input with fixed text. Imagine writing a letter or a report without being able to join sentences smoothly. Efficient concatenation also affects program speed and memory use, especially when working with large or many strings.
Where it fits
Before learning string concatenation, you should understand what strings are and basic operators in C#. After mastering concatenation, you can explore string formatting, interpolation, and performance optimization techniques like using StringBuilder.
Mental Model
Core Idea
String concatenation is like gluing pieces of paper with words on them to make one longer sentence.
Think of it like...
Imagine you have several small sticky notes with words written on them. When you stick them side by side, you create a longer message. Each sticky note is a string, and sticking them together is concatenation.
┌─────────┐   +   ┌─────────┐   =   ┌────────────────────┐
│ "Hello"│       │ " World"│       │ "Hello World"      │
└─────────┘       └─────────┘       └────────────────────┘
Build-Up - 6 Steps
1
FoundationBasic string concatenation with +
🤔
Concept: Using the + operator to join two strings simply.
string first = "Hello"; string second = "World"; string combined = first + " " + second; Console.WriteLine(combined);
Result
Hello World
Understanding that the + operator can join strings directly is the simplest way to combine text in C#.
2
FoundationStrings are immutable in C#
🤔
Concept: Strings cannot be changed after creation; concatenation creates new strings.
string a = "Hi"; string b = a + " there"; // 'a' remains "Hi", 'b' is a new string "Hi there"
Result
a = "Hi" b = "Hi there"
Knowing strings are immutable helps explain why concatenation creates new strings and affects memory.
3
IntermediateConcatenation performance with many strings
🤔Before reading on: Do you think using + repeatedly for many strings is fast or slow? Commit to your answer.
Concept: Repeated + concatenation creates many temporary strings, which can slow down performance.
string result = ""; for (int i = 0; i < 5; i++) { result += i.ToString() + ","; } Console.WriteLine(result);
Result
0,1,2,3,4,
Understanding that each + creates a new string helps explain why this approach is inefficient for many concatenations.
4
IntermediateUsing StringBuilder for efficient concatenation
🤔Before reading on: Do you think StringBuilder changes the original strings or builds a new one? Commit to your answer.
Concept: StringBuilder allows building a string efficiently by modifying an internal buffer instead of creating new strings each time.
var sb = new System.Text.StringBuilder(); for (int i = 0; i < 5; i++) { sb.Append(i); sb.Append(","); } Console.WriteLine(sb.ToString());
Result
0,1,2,3,4,
Knowing StringBuilder modifies a buffer internally explains why it is faster and uses less memory for many concatenations.
5
AdvancedCompiler optimization with string concatenation
🤔Before reading on: Does the compiler combine string literals at compile time or at runtime? Commit to your answer.
Concept: The C# compiler combines constant string literals at compile time to optimize performance.
string s = "Hello" + " " + "World"; Console.WriteLine(s);
Result
Hello World
Understanding compile-time concatenation helps explain why some concatenations have no runtime cost.
6
ExpertString interning and concatenation effects
🤔Before reading on: Do concatenated strings always get interned automatically? Commit to your answer.
Concept: String interning stores one copy of identical strings to save memory, but concatenated strings are interned only if explicitly requested.
string a = "Hello" + "World"; string b = string.Intern(a); Console.WriteLine(object.ReferenceEquals(a, b));
Result
False
Knowing that concatenated strings are not interned by default prevents mistaken assumptions about memory use and equality.
Under the Hood
When you concatenate strings with +, C# creates a new string object by copying the characters from the original strings into a new memory space. Because strings are immutable, the originals stay unchanged. For many concatenations, this creates many temporary strings, which can slow down the program and increase memory use. StringBuilder uses a resizable buffer internally to append characters without creating new string objects each time, improving performance.
Why designed this way?
Strings are immutable in C# to make them thread-safe and predictable. The + operator is simple and intuitive for small concatenations. However, for performance, StringBuilder was introduced to handle many concatenations efficiently. The compiler optimizes constant strings at compile time to reduce runtime overhead. Interning was designed to save memory by reusing identical strings but does not automatically apply to runtime concatenations to avoid complexity and overhead.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ String A     │       │ String B     │       │ New String    │
│ "Hello"     │  +    │ " World"    │  =>   │ "Hello World"│
└───────────────┘       └───────────────┘       └───────────────┘
        │                       │                      ▲
        │                       │                      │
        └───────────────┬───────┘                      │
                        │                              │
                Immutable strings                     New object

StringBuilder internal buffer:
┌───────────────────────────────────────────────┐
│ 'H' 'e' 'l' 'l' 'o' ' ' 'W' 'o' 'r' 'l' 'd'   │
└───────────────────────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does using + for many concatenations always perform well? Commit to yes or no.
Common Belief:Using + repeatedly to concatenate many strings is fast and efficient.
Tap to reveal reality
Reality:Repeated + concatenations create many temporary strings, causing slow performance and high memory use.
Why it matters:Ignoring this can cause programs to run slowly or crash due to excessive memory use.
Quick: Are concatenated strings automatically interned? Commit to yes or no.
Common Belief:All strings created by concatenation are automatically interned and share memory.
Tap to reveal reality
Reality:Only compile-time constant strings are interned automatically; runtime concatenations are not interned unless explicitly requested.
Why it matters:Assuming automatic interning can lead to incorrect assumptions about string equality and memory usage.
Quick: Does the + operator modify the original strings? Commit to yes or no.
Common Belief:Using + changes the original strings by adding more text to them.
Tap to reveal reality
Reality:Strings are immutable; + creates a new string without changing the originals.
Why it matters:Misunderstanding immutability can cause bugs when expecting original strings to change.
Quick: Does the compiler combine all string concatenations at compile time? Commit to yes or no.
Common Belief:The compiler always combines all string concatenations into one string at compile time.
Tap to reveal reality
Reality:Only concatenations of constant strings are combined at compile time; others happen at runtime.
Why it matters:Expecting all concatenations to be optimized can lead to unexpected performance issues.
Expert Zone
1
StringBuilder's internal buffer size grows dynamically, but resizing too often can still hurt performance.
2
Using string interpolation (e.g., $"{var}") compiles down to String.Format calls, which have their own performance characteristics.
3
Interning strings manually can save memory but may increase startup time and complexity.
When NOT to use
Avoid using + for concatenating many strings in loops; prefer StringBuilder or string.Create for performance. For simple, few concatenations, + or string interpolation is fine. When working with immutable strings and needing thread safety, avoid mutable buffers.
Production Patterns
In production, use + or interpolation for small, readable concatenations. Use StringBuilder for building large strings or in loops. Use string interning carefully to reduce memory in large-scale applications. Profiling string usage helps optimize performance hotspots.
Connections
Immutable Data Structures
String immutability is an example of immutable data structures.
Understanding string immutability helps grasp why immutable data structures are safer and easier to reason about in concurrent programming.
Memory Management
String concatenation affects memory allocation and garbage collection.
Knowing how concatenation creates new objects clarifies how memory is used and reclaimed in managed languages like C#.
Human Language Writing
Concatenation is like joining words to form sentences.
Seeing string concatenation as building sentences helps understand the importance of order and spacing in text processing.
Common Pitfalls
#1Using + in a loop for many concatenations causes slow performance.
Wrong approach:string result = ""; for (int i = 0; i < 1000; i++) { result += i.ToString(); }
Correct approach:var sb = new System.Text.StringBuilder(); for (int i = 0; i < 1000; i++) { sb.Append(i.ToString()); } string result = sb.ToString();
Root cause:Not realizing that + creates new strings each time, causing many temporary objects and slow execution.
#2Expecting original strings to change after concatenation.
Wrong approach:string a = "Hi"; a += " there"; // Expect 'a' to be modified in place
Correct approach:string a = "Hi"; a = a + " there"; // 'a' now points to a new string; original is unchanged
Root cause:Misunderstanding string immutability and assignment behavior.
#3Assuming all concatenated strings are interned automatically.
Wrong approach:string a = "Hello" + "World"; string b = "HelloWorld"; bool same = object.ReferenceEquals(a, b); // Expect true
Correct approach:string a = string.Intern("Hello" + "World"); string b = "HelloWorld"; bool same = object.ReferenceEquals(a, b); // True
Root cause:Not knowing that runtime concatenations are not interned unless explicitly requested.
Key Takeaways
String concatenation joins multiple strings into one new string, but strings themselves never change.
Using + for many concatenations creates many temporary strings, which hurts performance and memory use.
StringBuilder is designed to efficiently build strings by modifying an internal buffer instead of creating new strings each time.
The C# compiler optimizes concatenation of constant strings at compile time, but runtime concatenations happen during execution.
String interning saves memory by reusing identical strings but does not automatically apply to concatenated strings created at runtime.