Menu
Coddy logo textTech

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 icon

Challenge

Beginner

You 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!

Cheat sheet

To insert variable values into strings, use string interpolation with $ and {}:

int age = 30;
string name = "Alice";
System.Console.WriteLine($"Name: {name}, Age: {age}");

Alternatively, use the + operator to concatenate strings:

System.Console.WriteLine("Name: " + name + " Age: " + age);

Try it yourself

using System;

public class Program {
    public static void Main(string[] args) {
        string rnd = Console.ReadLine();
        
        // Write your code below
        
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals