String
The string
type represents a sequence of zero or more Unicode characters. string
is an alias for String in .NET.
Although string
is a reference type, the equality operators (==
and !=
) are defined to compare the values of string
objects, not references. This makes testing for string equality more intuitive. For example:
string a = "hello";
string b = "h";
// Append to contents of 'b'
b += "ello";
Console.WriteLine(a == b);
Console.WriteLine((object)a == (object)b);
This displays "True" and then "False" because the content of the strings are equivalent, but a
and b
do not refer to the same string instance.
The + operator concatenates strings:
string a = "good " + "morning";
This creates a string object that contains "good morning".
Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string "h" is then eligible for garbage collection.
string b = "h";
b += "ello";
The [] operator can be used for readonly access to individual characters of a string
:
string str = "test";
char x = str[2]; // x = 's';
String literals are of type string
and can be written in two forms, quoted and @-quoted. Quoted string literals are enclosed in double quotation marks ("):
"good morning" // a string literal
String literals can contain any character literal. Escape sequences are included. The following example uses escape sequence \\
for backslash, \u0066
for the letter f, and \n
for newline.
string a = "\\\u0066\n";
Console.WriteLine(a);
Note
The escape code \udddd
(where dddd
is a four-digit number) represents the Unicode character U+dddd
. Eight-digit Unicode escape codes are also recognized: \Udddddddd
.
Verbatim string literals start with @
and are also enclosed in double quotation marks. For example:
@"good morning" // a string literal
The advantage of verbatim strings is that escape sequences are not processed, which makes it easy to write, for example, a fully qualified file name:
@"c:\Docs\Source\a.txt" // rather than "c:\\Docs\\Source\\a.txt"
To include a double quotation mark in an @-quoted string, double it:
@"""Ahoy!"" cried the captain." // "Ahoy!" cried the captain.
Example
class SimpleStringTest
{
static void Main()
{
string a = "\u0068ello ";
string b = "world";
Console.WriteLine( a + b );
Console.WriteLine( a + b == "Hello World" ); // == performs a case-sensitive comparison
}
}
/* Output:
hello world
False
*/