Strings

Intro

string in C# is a reference type (System.String) with immutable contents. That combination is important: assignment copies references, but any text change creates a new string value. Understanding this helps you choose between plain concatenation, interpolation, and StringBuilder in performance-sensitive paths.

Deeper Explanation

Core properties

var a = "hello";
var b = a;
b = b + "!";

Console.WriteLine(a); // hello
Console.WriteLine(b); // hello!

b = b + "!" creates a new string object; a remains unchanged.

String interning

String literals are interned by default, so identical literals can share the same instance:

var s1 = "dotnet";
var s2 = "dotnet";

Console.WriteLine(object.ReferenceEquals(s1, s2)); // True

Interning can reduce duplicate literal allocations, but it should not be used blindly for large dynamic text.

StringBuilder

Use StringBuilder when you perform many appends in loops or build large text incrementally.

var sb = new StringBuilder(capacity: 256);
for (var i = 0; i < 5; i++)
{
    sb.Append("item-").Append(i).AppendLine();
}

var result = sb.ToString();

Decision rule:

Pitfalls

Tradeoffs

Questions


Whats next