String Interpolation
Part of the Fundamentals section of Coddy's C# journey — lesson 32 of 69.
So far we have learned how to print simple strings, but sometimes we need to insert variable values into the string.
For example:
int age = 10;
System.Console.WriteLine("His age is: age");This will print "His age is: age" instead of "His age is: 10"
To solve this, we will use string interpolation:
int age = 30;
string name = "Alice";
double balance = 1500.75;
System.Console.WriteLine($"Name: {name}, Age: {age}, Balance: {balance}");$indicates that the string is an interpolated string.{}are placeholders for variables.
Another way to combine strings with variables is with the plus + operator:
System.Console.Write("Name: " + name + " Age: " + age + " Balance: " + balance);Challenge
BeginnerYou are given a code that stores a random string as input to a variable named rnd.
Print to the console "The input is: " and the random string that is inside the variable rnd, using string interpolation.
Check the test cases for examples!
Try it yourself
using System;
public class Program {
public static void Main(string[] args) {
string rnd = Console.ReadLine();
// Write your code below
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic Shortcuts5Operators Part 2
Comparison OperatorsLogical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3