C# String Immutability
In C#, strings are immutable, meaning that once a string is created, it cannot be changed. Any operation that appears to modify a string actually creates a new string object.
Key Topics
1. Understanding Immutability
Example: String Modification
string original = "Hello";
string modified = original + " World";
Console.WriteLine(original); // Outputs: Hello
Console.WriteLine(modified); // Outputs: Hello World
In this example, original
remains unchanged, and a new string modified
is created.
2. Effects on Performance
Because strings are immutable, concatenating strings in a loop can lead to performance issues due to the creation of multiple string objects.
Example: Inefficient String Concatenation
string result = "";
for(int i = 0; i < 1000; i++)
{
result += "*";
}
3. Using StringBuilder
as an Alternative
The StringBuilder
class provides a mutable string object, which is more efficient for frequent modifications.
Example: Efficient String Concatenation with StringBuilder
using System.Text;
StringBuilder sb = new StringBuilder();
for(int i = 0; i < 1000; i++)
{
sb.Append("*");
}
string result = sb.ToString();
Key Takeaways
- Strings are immutable; operations create new string instances.
- Frequent string modifications can lead to performance issues.
- Use
StringBuilder
for efficient string manipulation in loops.