6 Many programs format data into strings. C# 6 introduces a mechanism called string interpolation that enables you to insert values in string literals to create formatted strings. Figure 3.13 demonstrates this capability.
string
Variable personLine 10
string person = "Paul"; // variable that stores the string "Paul"
is a variable declaration statement (also called a declaration) that specifies the name (person
) and type (string
) of a variable used in this app. A variable is a location in the computer’s memory where a value can be stored for later use (in this case, line 11). Variables are declared with a name and a type before they’re used:
A variable’s name enables the app to access the corresponding value in memory— the name can be any valid identifier. (See Section 3.2 for identifier naming requirements.)
A variable’s type specifies what kind of information is stored at that location in memory. Variables of type string
store character-based information, such as the contents of the string literal "Paul"
. In fact, a string literal has type string
. (From this point forward we’ll use the type name string
when referring to strings.)
Like other statements, declaration statements end with a semicolon (;
).
string
InterpolationLine 11
Console.WriteLine($"Welcome to C# Programming, {person}!");
uses string
interpolation to insert the variable person
’s value ("Paul"
) into the string
that Console.WriteLine
is about to display. An interpolated string
must begin with a $
(dollar sign). Then, you can insert interpolation expressions enclosed in braces, {}
(e.g., {person}
), anywhere between the quotes (""
). When C# encounters an interpolated string
, it replaces each braced interpolation expression with the corresponding value—in this case, {person}
is replaced with Paul
, so line 11 displays
Welcome to C# Programming, Paul!