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 |
|
| Double quote |
|
| Backslash |
|
| Null |
|
| Alert |
|
| Backspace |
|
| Form feed |
|
| New line |
|
| Carriage return |
|
| Horizontal tab |
|
| Vertical tab |
|
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.
String Type
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";
Note
string is a reference type,
rather than a value type. Its equality operators, however, follow
value-type semantics:
string a = "test", b = "test"; Console.Write (a == b); // True
The escape sequences that are valid for char literals also work inside strings:
string ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access