The three examples below show you how to use variables within string literals in C#.
1. Using the $ symbol
string name = "John Doe";
int age = 99;
var output = $"{name} is {age} year old";
Console.WriteLine(output);
Output:
John Doe is 99 year old
2. Using + Operation
var a = "apple";
var b = "banana";
var c = "coconut";
Console.WriteLine("My favorite fruits are " + a + ", " + b + ", " + c + ".");
Output:
My favorite fruits are apple, banana, coconut.
3. Using String.Format
string title = "The Wonderful Game";
float price = 30.99f;
var message = string.Format("{0} costs {1}USD.", title, price);
Console.WriteLine(message);
Output:
The Wonderful Game costs 30.99USD.
Happy coding!