Home > Articles

Introducing C#

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Escaping Characters

In some cases, characters cannot be displayed directly. This can lead to problems. The next line shows what problems might occur:

("This is a quotation mark: " ");

We try to display a quotation mark, which leads to an error because the compiler cannot translate the code. The compiler has no chance to do so because there's no way to find out which quotation mark means what. To tell the C# compiler which character to display on screen, we can use a backslash. In the next example, you can see how the most important symbols can be displayed:

using System;

class  Hello
    public static void Main()
        Console.WriteLine("Single quote: \'");
        Console.WriteLine("Quotation mark: \"");
        Console.WriteLine("Backslash: \\");
        Console.WriteLine("Alert: \a ");
        Console.WriteLine("Backspace: -\b");
        Console.WriteLine("Formfeed: \f");
        Console.WriteLine("Newline: \n");
        Console.WriteLine("Carriage Return: \r");
        Console.WriteLine("Tabulator: before\tafter");
        Console.WriteLine("Tab: \v");
        Console.WriteLine("binary 0: \0");

Backspaces are important—in contrast to other characters, backspaces make it possible to delete other characters. Not all characters lead to real output. In case of binary zeros, nothing is displayed on screen:

[hs@localhost csharp]$ mcs hello6.cs; mono hello6.exe
Compilation succeeded
Single quote: '
Quotation mark: "
Backspace: -


Carriage Return:
Tabulator: before    after

binary 0:

Escaping characters is essential. Particularly when dealing with external data structures, databases, or XML, escaping is important. We'll get back to escaping later in this book.

Symbols for escaping special characters are important when talking about paths. Paths can contain a number of backslashes. Especially on Microsoft Windows systems, this is interesting subject matter that can be the root of evil. Therefore, C# provides a simple mechanism for escaping backslashes in a path. Let's look at an example:

using System;

class  Hello
    public static void Main()
        String error = "c:\new_pics";
        Console.WriteLine("Error: " + error + "\n");

        String correct = @"c:\new_pics";
        Console.WriteLine("Correct: " + correct);

The first string contains a hidden line feed that causes trouble when displaying the text on the screen. In the second example, we use verbatim strings—this is a special kind of string that escapes only quotation marks. The advantage of verbatim strings is that the programmer need not worry about symbols other than quotation marks.

Let's see what comes out when the program is started:

[hs@localhost mono]$ mono path.exe
Error: c:

Correct: c:\new_pics
  • + Share This
  • 🔖 Save To Your Account