C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Newlines: These are specified with either "\r\n" or just "\n." And tabs are specified with "\t."
Quotes: For quotes, we often use a backslash, but for a verbatim literal (prefixed with @), we use two quotes to mean a quote.
At symbol: Four of the string literals are prefixed with the @ symbol. This is the verbatim string literal syntax.
Tip: The C# compiler allows you to use real newlines in verbatim literals. You must encode quotation marks with double quotes.
C# program that uses string literals
using System;
class Program
{
static string _value1 = "String literal";
const string _value2 = "String literal 2";
const string _value3 = "String literal 3\r\nAnother line";
const string _value4 = @"String literal 4
Another line";
const string _value5 = "String literal\ttab";
const string _value6 = @"String literal\ttab";
static void Main()
{
//
// Execution engine begins here.
//
string test1 = "String literal \"1\"";
const string test2 = "String literal 2";
string test3 = @"String literal ""3""";
const string test4 = @"String literal 4";
//
// Print out the string literals.
//
Console.WriteLine(
"{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n{9}",
_value1, _value2, _value3, _value4, _value5, _value6,
test1, test2, test3, test4);
}
}
Output
String literal
String literal 2
String literal 3
Another line
String literal 4
Another line
String literal tab
String literal\ttab
String literal "1"
String literal 2
String literal "3"
String literal 4
Next: This program appears to concatenate 3 strings. When compiled the IL shows that only one string is used.
string.ConcatC# program that concats string literals
using System;
class Program
{
static void Main()
{
const string a = "Dot ";
const string b = "Net ";
const string c = "Perls";
Console.WriteLine(a + b + c);
}
}
Output
The Dev Codes
Intermediate language: IL
.method private hidebysig static void Main() cil managed
{
.entrypoint
// Code size 11 (0xb)
.maxstack 8
IL_0000: ldstr "The Dev Codes"
IL_0005: call void [mscorlib]System.Console::WriteLine(string)
IL_000a: ret
} // end of method Program::Main
Tip: There are several predefined streams in the metadata files, including the #Strings stream and the #US (user strings) stream.
Note: The execution engine stores the offsets and tables in memory and then reads a range in the #US stream.
Here: String literal constants are separated and shared. Applying constant folding manually is not required for performance.
Storage: If you use a certain string literal in many places in a program, it is stored only once in the user strings stream.
Thus: We see the compiler technique of constant folding applied to string literals in C# programs.