Strings and Characters

C#’s char type (aliasing the System.Char type) represents a Unicode character and occupies two bytes. A char literal is specified inside single quotes:

char c = 'A';       // Simple character

Escape sequences express characters that cannot be expressed or interpreted literally. An escape sequence is a backslash followed by a character with a special meaning. For example:

char newLine = '\n';
char backSlash = '\\';

The escape sequence characters are:

Char

Meaning

Value

\'

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

The \u (or \x) escape sequence lets you specify any Unicode character via its four-digit hexadecimal code.

char copyrightSymbol = '\u00A9';
char omegaSymbol     = '\u03A9';
char newLine         = '\u000A';

An implicit conversion from a char to a numeric type works for the numeric types that can accommodate an unsigned short. For other numeric types, an explicit conversion is required.

C#’s string type (aliasing the System.String type) represents an immutable sequence of Unicode characters. A string literal is specified inside double quotes:

string a = "Heat";

The escape sequences that are valid for char literals also work inside strings:

string a = "Here's a tab:\t";

The cost of this is that whenever you need a literal backslash, you must write it twice:

string a1 = "\\\\server\\fileshare\\helloworld.cs";

To avoid this problem, C# allows verbatim string literals. A verbatim string literal is prefixed with @ and does not support escape sequences. The following verbatim string is identical to the preceding one:

string a2 = @"\\server\fileshare\helloworld.cs";

A verbatim string literal can also span multiple lines. You can include the double quote character in a verbatim literal by writing it twice.