Why String Is Immutable in C#: Explanation and Examples
string is immutable to improve security, performance, and thread safety. Once created, a string object cannot be changed, so any modification creates a new string instead.Syntax
The string type in C# is a reference type that represents a sequence of characters. You declare strings using double quotes. Because strings are immutable, any operation that seems to change a string actually creates a new string object.
Example syntax:
string s = "hello";- declares a string variable.s = s + " world";- creates a new string by combining two strings.
string s = "hello"; s = s + " world"; Console.WriteLine(s);
Example
This example shows how strings behave as immutable objects. When you try to change a string, a new string is created instead of modifying the original.
using System; class Program { static void Main() { string original = "cat"; string modified = original.Replace('c', 'b'); Console.WriteLine("Original string: " + original); Console.WriteLine("Modified string: " + modified); } }
Common Pitfalls
Many beginners expect string operations to change the original string, but strings are immutable. This can cause unexpected behavior or performance issues if you modify strings repeatedly in a loop.
For example, concatenating strings in a loop creates many temporary strings, which is inefficient. Instead, use StringBuilder for multiple modifications.
using System; using System.Text; class Program { static void Main() { // Inefficient way: creates many strings string result = ""; for (int i = 0; i < 5; i++) { result += i.ToString(); } Console.WriteLine("Result with +: " + result); // Efficient way: use StringBuilder StringBuilder sb = new StringBuilder(); for (int i = 0; i < 5; i++) { sb.Append(i); } Console.WriteLine("Result with StringBuilder: " + sb.ToString()); } }
Quick Reference
- Immutable: Strings cannot be changed after creation.
- Modification: Operations create new string objects.
- Performance: Use
StringBuilderfor many changes. - Thread Safety: Immutability makes strings safe to share across threads.