C# String Interpolation: Combine Text and Variables
Exercise – Combine Strings Using String Interpolation
What is string interpolation?
String interpolation lets you insert values into a literal string by using a template that contains{ } expressions. Each expression evaluates to a value at runtime. To enable interpolation, prefix the string with the $ symbol.string message = greeting + " " + firstName + "!";
string message = $"{greeting} {firstName}!";
Use string interpolation to combine a literal string and a variable
Clear any previous code, then enter:string firstName = "Bob";
string message = $"Hello {firstName}!";
Console.WriteLine(message);
Output:
Hello Bob!Use string interpolation with multiple variables
You can include several expressions inside one interpolated string. Delete earlier code, then type:int version = 11;
string updateText = "Update to Windows";
string message = $"{updateText} {version}";
Console.WriteLine(message);
Output:
Update to Windows 11Avoid intermediate variables
Just like with concatenation, you can remove unnecessary temporary variables:int version = 11;
string updateText = "Update to Windows";
Console.WriteLine($"{updateText} {version}!");
Output:
Update to Windows 11!Combine verbatim literals and string interpolation
You can use both$ (interpolation) and @ (verbatim literal) together. This is especially useful when working with file paths.string projectName = "First-Project";
Console.WriteLine($@"C:\Output\{projectName}\Data");
Output:
C:\Output\First-Project\DataRecap
• String interpolation simplifies formatting and reduces unnecessary characters.• You can merge
@ and $ to create verbatim interpolated strings.• Interpolation improves readability and is ideal for complex string compositions.
Continue learning
Further reading: Microsoft documentation.
String interpolation troubleshooting
How can I print braces instead of starting an expression?
In an ordinary interpolated string, double the braces to print literal braces. For example, $"{{name}}" displays {name}; $"{name}" evaluates the variable name. These rules differ for raw interpolated strings, which are outside this beginner exercise.
Practice and check
Set name to Ada and compare those two expressions. Expected results: {name} and Ada. Also remove the $ once and observe that braces are then ordinary characters rather than substitutions.
Comments
Post a Comment