C#'s char
type aliasing the System.Char
type represents a Unicode character.
A char
literal is specified inside single quotes:
char c = 'A';
The code above creates a char type variable c
and assigns value A
to it.
Escape sequences express characters that cannot be expressed 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 shown in the following Table.
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 can
specify any Unicode character via its four-digit hexadecimal code.
For example,
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 = "java2s.com";
string
is a reference type, rather than a value type.
Its equality operators, however, follow value-type semantics:
string a = "test";
string b = "test";
Console.Write (a == b); // True
The escape sequences that are valid for char
literals also work inside strings:
string a = "Here's a tab:\t";
C# allows verbatim string literals.
A verbatim string literal is prefixed with @
and does not support escape sequences.
string a2 = @ "\\root\files\Main.cs";
A verbatim string literal can also span multiple lines:
string escaped = "First Line\r\nSecond Line";
string verbatim = @"First Line
Second Line";
You can include the double-quote character in a verbatim literal by writing it twice:
string xml = @"<emp id=""123""></emp>";
The +
operator concatenates two strings:
string s = "a" + "b";
A nonstring value's ToString
method is called on
that value. For example:
string s = "a" + 1; // a1