Getting started with C# LanguageVerbatim StringsOperatorsExtension MethodsCollection InitializersString InterpolationC# 6.0 FeaturesConstructors and FinalizersKeywordsGenericsReflectionInheritanceNull-Coalescing OperatorUsing StatementString Escape SequencesException HandlingNull-conditional OperatorsBuilt-in TypesLambda expressionsAsync-AwaitPropertiesThreadingUsing DirectiveMethodsYield KeywordEventsLINQ QueriesCommon String OperationsExpression TreesOverload ResolutionString.Formatnameof OperatorUnsafe Code in .NETInitializing PropertiesBindingList<T>ILGeneratorObject initializersXML Documentation CommentsPreprocessor directivesDynamic typeAnonymous typesStructsTuplesEnumAccess ModifiersTask Parallel LibraryAttributesGuidSingleton ImplementationDelegatesNullable typesGarbage Collector in .NetNetworkingArraysEquality OperatorLock StatementAction FiltersXmlDocument and the System.Xml namespaceDateTime MethodsBackgroundWorkerPolymorphismStatic ClassesIndexerIDisposable interfaceAliases of built-in typesImmutabilityXDocument and the System.Xml.Linq namespaceC# 7.0 FeaturesPerforming HTTP requestsGenerating Random Numbers in C#LoopingNamed ArgumentsDiagnosticsInterfacesIEnumerableNaming ConventionsAn overview of c# collectionsChecked and UncheckedRecursionFunctional ProgrammingLiteralsCastingNullReferenceExceptionFunc delegatesLINQ to XMLHash FunctionsHandling FormatException when converting string to other typesCryptography (System.Security.Cryptography)INotifyPropertyChanged interfaceValue type vs Reference typeC# 4.0 FeaturesIQueryable interfaceTask Parallel Library (TPL) Dataflow ConstructsStreamRuntime CompileConditional StatementsInteroperabilityOverflowEquals and GetHashCodeType ConversionParallel LINQ (PLINQ)String ManipulationString ConcatenatePartial class and methodsStopwatchesRegex ParsingC# ScriptC# 3.0 FeaturesAsync/await, Backgroundworker, Task and Thread ExamplesTimersFunction with multiple return valuesBinary SerializationMaking a variable thread safeIComparableCode ContractsIteratorsAssemblyInfo.cs ExamplesFile and Stream I/OCode Contracts and AssertionsCachingC# 5.0 FeaturesImplementing Flyweight Design PatternStringBuilderImplementing Decorator Design PatternAccessing DatabasesT4 Code GenerationMicrosoft.Exchange.WebServices.NET Compiler Platform (Roslyn)Data AnnotationUsing SQLite in C#System.Management.AutomationFileSystemWatcherSystem.DirectoryServices.Protocols.LdapConnectionNamed and Optional ArgumentsComments and regionsC# Authentication handlerPointers & Unsafe CodePointersHow to use C# Structs to create a Union type (Similar to C Unions)BigIntegerDependency InjectionReactive Extensions (Rx)Creational Design PatternsCreating a Console Application using a Plain-Text Editor and the C# Compiler (csc.exe)Reading and writing .zip filesGeneric Lambda Query BuilderImport Google ContactsLambda ExpressionsCLSCompliantAttributeObservableCollection<T>Synchronization Context in Async-AwaitICloneableRead & Understand StacktracesLinq to ObjectsASP.NET IdentityAccess network shared folder with username and passwordAsynchronous SocketStructural Design PatternsO(n) Algorithm for circular rotation of an arrayCreating Own MessageBox in Windows Form ApplicationIncluding Font ResourcesObject Oriented Programming In C#Using json.netGetting Started: Json with C#Windows Communication Foundation

String Escape Sequences

Other topics

Remarks:

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

Unicode character escape sequences

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

Apostrophes

char apostrophe = '\'';

Backslash

char oneBackslash = '\\';

Escaping special symbols in string literals

Backslash

// 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.

Quotes

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.

Newlines

Verbatim string literals can contain newlines:

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

Both variables will contain the same text.

Unrecognized escape sequences produce compile-time errors

The following examples will not compile:

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

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

Using escape sequences in identifiers

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.)

Syntax:

  • \' β€” 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)

Contributors

Topic Id: 39

Example Ids: 162,164,166,358,10191

This site is not affiliated with any of the contributors.