\e
Escape Sequence in C# 13 — A Cleaner Way to Emit the ESC Character
In C# 13, the language introduces a small yet helpful improvement to how we write character and string literals — a new escape sequence: \e
, which represents the ESC (escape) character U+001B
.
Historically, representing this control character required the use of Unicode escape sequences like \u001B
or hexadecimal escapes like \x1b
. However, \x1b
had a hidden risk: it could be unintentionally extended by following characters, leading to unexpected behavior in your code.
What Is \e
?
The new escape sequence:
string esc = "\e"; // Equivalent to '\u001B' (ESC)
This is now the recommended way to include the ESC (escape) control character, which is often used in:
- ANSI escape codes for terminal coloring and control
- Custom serial protocols
- Legacy device communication
Before C# 13
string oldWay1 = "\u001B"; // Safe but verbose
string oldWay2 = "\x1b"; // Compact but potentially ambiguous!
❗ Problem with \x1b
:
It might absorb valid hex characters after 1b
, e.g.:
string broken = "\x1b2F"; // This becomes one char: '\u1b2F'
You expected: 'ESC'
+ '2'
+ 'F'
You got: a single corrupted character.
C# 13 Solution
string esc = "\e"; // Always emits '\u001B'
string ansi = "\e[31mRed"; // Safe, readable, no surprises
Simple, readable, unambiguous. 🎉
Practical Example: ANSI Coloring
Console.Write("\e[31m"); // Start red
Console.Write("Hello ");
Console.Write("\e[32m"); // Start green
Console.Write("World");
Console.Write("\e[0m"); // Reset
Outputs:
Hello
(in red), World
(in green), then resets.
📦 Summary Table
Escape | Meaning | Notes |
---|---|---|
\u001B |
ESC | Safe but verbose |
\x1b |
ESC | Risky when followed by hex |
\e |
ESC | ✅ Safe, short, and clear |
Learn More
Final Thoughts
The new \e
escape sequence may seem small, but it solves a subtle and real problem that impacted developers working with low-level communication, terminals, or legacy hardware. It makes your intentions explicit, your code safer, and your strings more readable.
Sometimes the smallest features have the biggest impact on correctness and maintainability.
Written by: [Cristian Sifuentes] – C# Syntax Aficionado | Terminal UI Engineer | Clean Code Champion
Still using \u001B
in your console libraries? Try \e
and simplify!