3.5 String Interpolation

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.

Fig. 3.13 Inserting content into a string with string interpolation.

Alternate View

  1   // Fig. 3.13: Welcome4.cs
  2   // Inserting content into a string with string interpolation.
  3   using System;
  4
  5   class Welcome4
  6   {
  7      // Main method begins execution of C# app
  8      static void Main()
  9      {
 10         string person = "Paul"; // variable that stores the string "Paul"
 11         Console.WriteLine($"Welcome to C# Programming, {person}!");      
 12      } // end Main
 13   } // end class Welcome4

Welcome to C# Programming, Paul!

Declaring the string Variable person

Line 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 Interpolation

Line 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!
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset