CSharp/C# Tutorial - C# Characters and Strings

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

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.

\'Single quote0x0027
\"Double quote0x0022
\fForm feed0x000C
\nNew line0x000A
\rCarriage return0x000D
\tHorizontal tab0x0009
\vVertical tab0x000B

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'; 

Char Conversions

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 = "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"; 

Verbatim string literals

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>"; 

String concatenation

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