Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
C# provides a feature called string interpolation, that lets you substitute the result of C# code into the middle of a string.
- Having to remember to put a space on either side of the concatenated variable is awkward:
Console.WriteLine("You entered " + entry + " cans");
- C# provides a feature called string interpolation, that lets you substitute the result of C# code into the middle of a string.
- Interpolation can make it easier to format strings like this one.
- To use interpolation in C#, type a dollar sign (
$
) right before the opening quote of a string. - Anywhere you want within the string, you can include an interpolation marker. A marker consists of an opening curly brace, and a closing curly brace.
- You can include any C# code you want between the curly braces.
- I'll do a math operation: `Console.WriteLine($"aaa {1 + 2} bbb");
- The code will be evaluated, the result will be converted to a string, and the resulting string will be substituted for the interpolation marker within the containing string:
aaa 3 bbb
- Next, I'll use the property
System.DateTime.Now
, which you can think of like a variable that's always set to the current date and time - Because we have a
using System;
directive at the top of this file, I can take off theSystem
namespace:Console.WriteLine($"aaa {DateTime.Now} bbb");
- That gives me the output:
aaa 5/21/19 4:00:34 PM bbb
- Lets us embed the values of variables:
string name = "Jay";
Console.WriteLine($"Hello {name}!");
- We can include multiple interpolation markers into a single string:
Console.WriteLine($"{DateTime.Now} {name}");
Let's try improving our cat food store code using string interpolation.
- We'll add a dollar sign at the start of the string.
- We'll remove the plus signs to combine all the concatenated strings into one.
- In their place, we'll add an interpolation marker that inserts the value of the
answer
variable:Console.WriteLine($"You entered {answer} cans");
- It's easy to remember to put spaces surrounding the interpolation marker because it would look funny if we didn't.
You can see in the output that it's inserting the value of the answer
variable into the string, and it's surrounded by spaces as it should be.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up