csharp-strings

What are Strings and How They Work in C#

  • 3 min

In C#, a string is a data type that represents a sequence of Unicode characters, allowing us to handle text conveniently.

It is an immutable object of the System.String class, meaning that once created, it cannot be modified.

  • Immutability: Once created, a string cannot be modified. Any operation that modifies the content of a string generates a new string object.
  • Unicode-based: strings in C# use Unicode encoding, allowing them to represent characters from virtually all languages and symbols.

Declaration and Literals

We have several ways to declare strings (almost too many), each with its special characteristics.

Standard Literal

The classic one. Requires escaping special characters with the backslash \.

string ruta = "C:\\Windows\\System32"; // We need a double backslash
string salto = "Hola\nMundo";          // \n is a line break

Copied!

Verbatim Strings (@)

If we put an at sign @ in front, we tell C# to ignore escape characters. It’s useful for file paths or regular expressions (RegEx).

string ruta = @"C:\Windows\System32"; // Much cleaner!
string html = @"<div class=""box"">"; // Quotes are escaped by doubling them

Copied!

String Interpolation ($)

Introduced in C# 6, it’s the modern way to format. Allows embedding variables directly into the text.

int edad = 30;
string mensaje = $"Tengo {edad} años";

Copied!

Raw String Literals (""")

Since C# 11, allows writing multi-line text blocks without worrying about quotes or escapes. Ideal for embedded JSON, XML, or SQL.

string json = """
    {
        "nombre": "Luis",
        "web": "luisllamas.es"
    }
    """;

Copied!
  • It behaves similarly to a value type (it has value semantics).
  • But technically it is a Reference Type.

This means the variable on the Stack only holds a memory address. The actual text content lives in the Heap.

However, C# overloads the equality operator == to compare the content and not the reference. That’s why "hola" == "hola" returns true, even though they are two distinct objects in memory.

Immutability

The most important property, strings in C# are immutable. That is, once a string is created in memory, it cannot be changed. Ever.

“But Luis, if I do this, the text changes”

string texto = "Hola";
texto = texto + " Mundo";
Copied!

No, it doesn’t change. What happens internally is:

“Hola” is created in memory.

” Mundo” is created in memory.

A third, new string containing “Hola Mundo” is created.

The variable texto points to the new one.

The original “Hola” is left “orphaned” in memory waiting for the Garbage Collector.

The main reason for Strings being immutable is security and error prevention (in fact, it’s common in many languages).

This characteristic is very important for performance. If you concatenate strings inside a for loop thousands of times, you are creating thousands of garbage objects that choke memory. For that, we will use StringBuilder.

Empty String vs Null

Another classic error point.

  • null: The variable points to nothing. No object exists. If you try to access it: NullReferenceException.
  • String.Empty or "": An object exists in memory, but it has a length of 0. It’s valid text.
  • WhiteSpace: Text that only contains spaces, tabs, or line breaks.

To check this robustly, always use:

if (string.IsNullOrEmpty(texto)) { ... }
if (string.IsNullOrWhiteSpace(texto)) { ... } // Includes whitespace

Copied!