Introduction

I have spent numerous hours searching for solutions to programming problems that I think should have a more accessible solution. This blog will contain my experiences and the solutions that I found. Your comments are welcome of course.

Thursday, June 19, 2008

C# Escape Characters

When trying to use a double quote or a single quote as part of a string you can use an escape character "\" to let the compiler know it is part of the string and not a regular quotation in the C# Language.

When declaring a string variable, certain characters can't, for various reasons, be included in the usual way. C# supports two different solutions to this problem.

The first approach is to use 'escape sequences'. For example, suppose that we want to set variable a to the value:

"Hello World
How are you"

We could declare this using the following command, which contains escape sequences for the quotation marks and the line break.

string a = "\"Hello World\nHow are you\"";

The following table gives a list of the escape sequences for the characters that can be escaped in this way:

The second approach is to use 'verbatim string' literals. These are defined by enclosing the required string in the characters @" and ". To illustrate this, to set the variable 'path' to the following value:

C:\My Documents\

we could either escape the back-slash characters

string path = "C:\\My Documents\\"

or use a verbatim string thus:

string path = @"C:\MyDocuments\"

Usefully, strings written using the verbatim string syntax can span multiple lines, and whitespace is preserved. The only character that needs escaping is the double-quote character, the escape sequence for which is two double-quotes together. For instance, suppose that you want to set the variable 'text' to the following value:

the word "big" contains three letters.

Using the verbatim string syntax, the command would look like this:

string text = @"the word ""big"" contains three letters."