0
0
CsharpHow-ToBeginner · 3 min read

Why String Is Immutable in C#: Explanation and Examples

In C#, 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.
csharp
string s = "hello";
s = s + " world";
Console.WriteLine(s);
Output
hello world
💻

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.

csharp
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);
    }
}
Output
Original string: cat Modified string: bat
⚠️

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.

csharp
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());
    }
}
Output
Result with +: 01234 Result with StringBuilder: 01234
📊

Quick Reference

  • Immutable: Strings cannot be changed after creation.
  • Modification: Operations create new string objects.
  • Performance: Use StringBuilder for many changes.
  • Thread Safety: Immutability makes strings safe to share across threads.

Key Takeaways

Strings in C# are immutable, meaning they cannot be changed after creation.
Any change to a string creates a new string object in memory.
Immutability improves security, thread safety, and performance in many cases.
Avoid repeated string concatenation in loops; use StringBuilder instead.
Understanding string immutability helps prevent bugs and optimize code.