Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharpNotesForProfessionals.pdf
Скачиваний:
57
Добавлен:
20.05.2023
Размер:
6.12 Mб
Скачать

Chapter 16: String Escape Sequences

Section 16.1: 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.

Section 16.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"

Section 16.3: Escaping special symbols in character literals

Apostrophes

char apostrophe = '\'';

Backslash

char oneBackslash = '\\';

Section 16.4: Using escape sequences in identifiers

Escape sequences are not restricted to string and char literals.

GoalKicker.com – C# Notes for Professionals

76

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

Section 16.5: 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.

GoalKicker.com – C# Notes for Professionals

77