ASCII characters below 32 are non-printable and are often represented by escape sequences such as \n
for newline and \t
for tab. The escape sequence \u001b
or \x1b
is used to represent the ASCII escape character (27) which is often used in terminal applications to control text formatting.
C# 13 introduces a new \e
escape sequence for character literals which is easier to read and less error-prone than the \u001b
and \x1b
escape sequences.
Code
C#
const string ansiClearScreen = "\e[2J";
string ansiSetForeground(Color color) => $"\e[38;2;{color.Red};{color.Green};{color.Blue}m";
C#
const string ansiClearScreen = "\u001b[2J";
string ansiSetForeground(Color color) => $"\x1b[38;2;{color.Red};{color.Green};{color.Blue}m";
Notes
- The older
\x1b
escape sequence is error-prone as\x
is variable-length and valid hex characters following the1b
change it from ESC to a different unicode character.