C Sharp TutorialC Sharp .NET Compiler Platform (Roslyn)C Sharp 3.0 FeaturesC Sharp 4.0 FeaturesC Sharp 5.0 FeaturesC Sharp 6.0 FeaturesC Sharp 7.0 FeaturesC Sharp Access ModifiersC Sharp Access network shared folder with username and passwordC Sharp Accessing DatabasesC Sharp Action FiltersC Sharp Aliases of built-in typesC Sharp an overview of collectionsC Sharp Anonymous typesC Sharp ArraysC Sharp ASP.NET IdentityC Sharp AssemblyInfo.cs ExamplesC Sharp Async-AwaitC Sharp Async/await, Backgroundworker, Task and Thread ExamplesC Sharp Asynchronous SocketC Sharp AttributesC Sharp Authentication handlerC Sharp BackgroundWorkerC Sharp BigIntegerC Sharp Binary SerializationC Sharp BindingListC Sharp Built-in TypesC Sharp CachingC Sharp CastingC Sharp Checked and UncheckedC Sharp CLSCompliantAttributeC Sharp Code ContractsC Sharp Code Contracts and AssertionsC Sharp Collection InitializersC Sharp Comments and regionsC Sharp Common String OperationsC Sharp Conditional StatementsC Sharp Constructors and FinalizersC Sharp Creating Own MessageBox in Windows Form ApplicationC Sharp Creational Design PatternsC Sharp Cryptography (System.Security.Cryptography)C Sharp Data AnnotationC Sharp DateTime MethodsC Sharp DelegatesC Sharp Dependency InjectionC Sharp DiagnosticsC Sharp Dynamic typeC Sharp EnumC Sharp Equality OperatorC Sharp Equals and GetHashCodeC Sharp EventsC Sharp Exception HandlingC Sharp Expression TreesC Sharp Extension MethodsC Sharp File and Stream I/OC Sharp FileSystemWatcherC Sharp Func delegatesC Sharp Function with multiple return valuesC Sharp Functional ProgrammingC Sharp Garbage Collector in .NETC Sharp Generating Random NumbersC Sharp Generic Lambda Query BuilderC Sharp GenericsC Sharp Getting Started: Json with C SharpC Sharp GuidC Sharp Handling FormatException when converting string to other typesC Sharp Hash FunctionsC Sharp ICloneableC Sharp IComparableC Sharp IDisposable interfaceC Sharp IEnumerableC Sharp ILGeneratorC Sharp ImmutabilityC Sharp Implementing Decorator Design PatternC Sharp Implementing Flyweight Design PatternC Sharp Import Google ContactsC Sharp Including Font ResourcesC Sharp IndexerC Sharp InheritanceC Sharp Initializing PropertiesC Sharp INotifyPropertyChanged interfaceC Sharp InterfacesC Sharp InteroperabilityC Sharp IQueryable interfaceC Sharp IteratorsC Sharp KeywordsC Sharp Lambda expressionsC Sharp Lambda ExpressionsC Sharp LINQ QueriesC Sharp LINQ to Objects

C Sharp String Escape Sequences

From WikiOD

Syntax[edit | edit source]

  • \' — single quote (0x0027)
  • \" — double quote (0x0022)
  • \\ — backslash (0x005C)
  • \0 — null (0x0000)
  • \a — alert (0x0007)
  • \b — backspace (0x0008)
  • \f — form feed (0x000C)
  • \n — new line (0x000A)
  • \r — carriage return (0x000D)
  • \t — horizontal tab (0x0009)
  • \v — vertical tab (0x000B)
  • \u0000 - \uFFFF — Unicode character
  • \x0 - \xFFFF — Unicode character (code with variable length)
  • \U00000000 - \U0010FFFF — Unicode character (for generating surrogates)

Remarks[edit | edit source]

String escape sequences are transformed to the corresponding character at compile time. Ordinary strings that happen to contain backwards slashes are not transformed.

For example, the strings notEscaped and notEscaped2 below are not transformed to a newline character, but will stay as two different characters ('\' and 'n').

string escaped = "\n";
string notEscaped = "\\" + "n";
string notEscaped2 = "\\n";

Console.WriteLine(escaped.Length); // 1
Console.WriteLine(notEscaped.Length); // 2            
Console.WriteLine(notEscaped2.Length); // 2

Escaping special symbols in string literals[edit | edit source]


// The filename will be c:\myfile.txt in both cases
string filename = "c:\\myfile.txt";
string filename = @"c:\myfile.txt";

The second example uses a verbatim string literal, which doesn't treat the backslash as an escape character.


string text = "\"Hello World!\", said the quick brown fox.";
string verbatimText = @"""Hello World!"", said the quick brown fox.";

Both variables will contain the same text.

"Hello World!", said the quick brown fox.


Verbatim string literals can contain newlines:

string text = "Hello\r\nWorld!";
string verbatimText = @"Hello

Both variables will contain the same text.

Unicode character escape sequences[edit | edit source]

string sqrt = "\u221A";      // √
string emoji = "\U0001F601"; // 😁
string text = "\u0022Hello World\u0022"; // "Hello World"
string variableWidth = "\x22Hello World\x22"; // "Hello World"

Escaping special symbols in character literals[edit | edit source]


char apostrophe = '\'';


char oneBackslash = '\\';

Using escape sequences in identifiers[edit | edit source]

Escape sequences are not restricted to string and char literals.

Suppose you need to override a third-party method:

protected abstract IEnumerable<Texte> ObtenirŒuvres();

and suppose the character Πis not available in the character encoding you use for your C# source files. You are lucky, it is permitted to use escapes of the type \u#### or \U######## in identifiers in the code. So it is legal to write:

protected override IEnumerable<Texte> Obtenir\u0152uvres()
    // ...

and the C# compiler will know Πand \u0152 are the same character.

(However, it might be a good idea to switch to UTF-8 or a similar encoding that can handle all characters.)

Unrecognized escape sequences produce compile-time errors[edit | edit source]

The following examples will not compile:

string s = "\c";
char c = '\c';

Instead, they will produce the error Unrecognized escape sequence at compile time.