The string data type is used to store string constants. They are delimited by double quotes.
string a = "Hello";
String Concatenation
The concatenation operator
(+) can combine strings together. It also has an accompanying assignment operator (+=), which appends a string to another and creates a new string.
string b = a + " World"; // Hello World
a += " World"; // Hello World
When one of the operands is not of a string type, the concatenation operator will implicitly convert the non-string type into a string, making the following assignment valid.
int i = 1;
string c = i + " is " + 1; // 1 is 1
The string conversion is performed implicitly using the ToString method
. All types in .NET have this method, which provides a string representation of a variable or expression. As seen in the next example, the string conversion can also be made explicitly.
string d = i.ToString() + " is " + 1.ToString(); // 1 is 1
Another way to compile strings is to use string interpolation. This feature was added in C# 6.0 and enables expressions placed inside curly brackets to be evaluated within a string. To perform string interpolation, a dollar sign ($) is placed before the string.
string s1 = "Hello";
string s2 = "World";
string s = $"{s1} {s2}"; // Hello World
Escape Characters
A statement can be broken up across multiple lines, but a string constant must be on a single line. In order to divide it, the string constant has to first be split up using the concatenation operator.
string myString
= "Hello " +
"World";
To add new lines into the string itself, the escape character (
) is used.
string myString = "Hello
World";
This backslash notation is used to write special characters, such as a backslash or double quote. Among the special characters is also a Unicode character notation for writing any character.
Character | Meaning | Character | Meaning |
---|---|---|---|
| Newline | f | Form feed |
| Horizontal tab | a | Alert sound |
v | Vertical tab | ' | Single quote |
Backspace | " | Double quote | |
| Carriage return | \ | Backslash |