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

Verbatim Strings

Other topics

Remarks:

To concatenate string literals, use the @ symbol at the beginning of each string.

var combinedString = @"\t means a tab" + @" and \n means a newline";

Multiline Strings

var multiLine = @"This is a 

multiline paragraph";

Output:

This is a

multiline paragraph

Live Demo on .NET Fiddle

Multi-line strings that contain double-quotes can also be escaped just as they were on a single line, because they are verbatim strings.

var multilineWithDoubleQuotes = @"I went to a city named

                        ""San Diego""

                      during summer vacation.";

Live Demo on .NET Fiddle

It should be noted that the spaces/tabulations at the start of lines 2 and 3 here are actually present in the value of the variable; check this question for possible solutions.

Escaping Double Quotes

Double Quotes inside verbatim strings can be escaped by using 2 sequential double quotes "" to represent one double quote " in the resulting string.

var str = @"""I don't think so,"" he said.";
Console.WriteLine(str);

Output:

"I don't think so," he said.

Live Demo on .NET Fiddle

Interpolated Verbatim Strings

Verbatim strings can be combined with the new String interpolation features found in C#6.

Console.WriteLine($@"Testing \n 1 2 {5 - 2}
New line");

Output:

Testing \n 1 2 3
New line

Live Demo on .NET Fiddle

As expected from a verbatim string, the backslashes are ignored as escape characters. And as expected from an interpolated string, any expression inside curly braces is evaluated before being inserted into the string at that position.

Verbatim strings instruct the compiler to not use character escapes

In a normal string, the backslash character is the escape character, which instructs the compiler to look at the next character(s) to determine the actual character in the string. (Full list of character escapes)

In verbatim strings, there are no character escapes (except for "" which is turned into a "). To use a verbatim string, just prepend a @ before the starting quotes.

This verbatim string

var filename = @"c:\temp\newfile.txt"

Output:

c:\temp\newfile.txt

As opposed to using an ordinary (non-verbatim) string:

var filename = "c:\temp\newfile.txt"

that will output:

c:    emp
ewfile.txt

using character escaping. (The \t is replaced with a tab character and the \n is replace with a newline.)

Live Demo on .NET Fiddle

Syntax:

  • @"verbatim strings are strings whose contents are not escaped, so in this case \n does not represent the newline character but two individual characters: \ and n. Verbatim strings are created prefixing the string contents with the @ character"

  • @"To escape quotation marks, ""double quotation marks"" are used."

Contributors

Topic Id: 16

Example Ids: 40,41,42,2534

This site is not affiliated with any of the contributors.