In C# 6.0 string interpolation introduced. In this article, we learn what String Interpolation is and how it can accomplish in previous C# versions. Before C# 6.0, string.Format() was used to format the string as shown below.
class Program
{
static void Main(string[] args)
{
string str1 = "First String";
string str2 = "Second String";
string finalString = string.Format("There are two strings and those are {0} and {1}", str1, str2);
Console.WriteLine(finalString);
Console.ReadLine();
}
}
We can get same output as above code gives with less code in C# by using string interpolation. Open Microsoft Visual Studio 2015, add below code.
class Program
{
static void Main(string[] args)
{
string str1 = "First String";
string str2 = "Second String";
string finalString = $"There are two strings and those are {str1} and {str2}";
Console.WriteLine(finalString);
Console.ReadLine();
}
}
As shown, we are replacing the strings by placing them in { & } symbols and place $ symbol before string. Run the application and it produces the same output as below.
With less code, we accomplished the same output in C# 6.0 by using String Interpolation.
We can apply string interpolation not only just for strings, but we can also implement this for methods also. Let’s have a simple method for adding two integers. Display the sum of two integers with the help of string interpolation as shown below.
class Program
{
static void Main(string[] args)
{
int number1 = 100;
int number2 = 200;
string finalString = $"The sum of two integers {number1} and {number2} is {Sum(number1, number2)}";
Console.WriteLine(finalString);
Console.ReadLine();
}
private static int Sum(int n1, int n2)
{
return n1 + n2;
}
}
Run the application; it displays the sum of the two integers as output as shown below.