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 ...
Get C# 5.0 Pocket Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.