Search⌘ K
AI Features

String Immutability

Explore the concept of string immutability in C# and understand how it differs from mutable types like arrays. This lesson helps you grasp why strings cannot be changed after creation, the impact on string algorithms, and why new string objects are created for modifications. You will learn the importance of immutability in ensuring safe and predictable string handling and its effect on designing efficient string operations in C#.

We'll cover the following...

By this point, you have seen that individual characters in strings can be accessed and traversed, and the length of a string can be determined using ideas similar to those used with arrays. That structural similarity makes strings feel familiar. However, there is one important place where strings and arrays behave very differently, and it shows up the moment any attempt is made to modify a string. Understanding this difference is not just a matter of knowing a C# rule. It directly affects how string algorithms are designed, how their performance is analyzed, and why certain patterns appear in string code again and again.

Attempting to modify a string

Consider a simple array of integers. Changing the first element is a straightforward operation where the value at that position is simply overwritten.

C# 14.0
int[] arr = { 1, 2, 3, 4, 5 };
arr[0] = 99;
Console.WriteLine($"[{string.Join(", ", arr)}]"); // [99, 2, 3, 4, 5]

Now consider trying to do the same thing with a string.

C# 14.0
string s = "hello";
s[0] = 'H'; // CS0200: string characters are read-only

The compiler error shows that a character in a string cannot be replaced in the same way that an ...