C# tip: modern string indexing (counting from the end and slicing)

Posted: (EET/GMT+2)

 

If you need to index strings from the end in modern C#, there's a clean built-in way to do it: use counting from the right, instead of left.

Starting with C# 8, strings support the Index and Range syntax. Instead of manual length calculations, you can index from the end using the ^ operator.

string text = "HelloWorld";

char lastChar = text[^1];
string lastFive = text[^5..];

In this example, ^1 means "one character from the end". This replaces older patterns like text[text.Length - 1].

You can also slice strings using ranges:

string firstFive = text[..5];
string middleOnes = text[2..7];

This works the same way for arrays and spans, and avoids off-by-one errors that tend to creep into manual index math.

Hope this helps!