String Interpolation is introduced in C# 6.0. String Interpolation is the feature to insert value(s) into the string. Confused?
Let's start with string formatter.
Before C#6.0, we used to write, as shown below.
- string log = string.Format("Values for the sum are value1:{0} and Value2:{1}", value1, value2);
- string log = $"Values for the sum are value1:{value1} and Value2:{value2}";
Let's take a simple example of calculating the sum of 2 integers. The code snippet is mentioned below.
- private static int CalculateSum(int value1, int value2)
- {
- string log = $ "Values for the sum are value1:{value1} and Value2:{value2}";
- Console.WriteLine(log);
- return value1 + value2;
- }
- static void Main(string[] args) {
- int sum = CalculateSum(5, 6);
- Console.WriteLine($ "sum is:{sum}");
- Console.ReadLine();
- }
Wait, you might be wondering what's the difference between string.format and string interpolation. Correct? Let's check the decompiled code of calculatesum code snippet in dotpeek tool.
Note
There are many decompiler tools available, for example, Reflector, ILspy etc. To know more about how dotpeek works, please refer to the link, mentioned below.
- internal class Program
- {
- private static void Main(string[] args) {
- Console.WriteLine(string.Format("sum is:{0}", (object) Program.CalculateSum(5, 6)));
- Console.ReadLine();
- }
- private static int CalculateSum(int value1, int value2) {
- Console.WriteLine(string.Format("Values for the sum are value1:{0} and Value2:{1}", (object) value1, (object) value2));
- return value1 + value2;
- }
One more question might be in your mind, whether the string interpolation is only relevant to data types like int, string, float etc. or not.
Answer is no. You can use string interpolation with an array, method, expression and so on.
Let's see how we can use string interpolation with Method and Expression.
Below is the code snippet for the expression.
- private static string Multiplication(int value1, int value2)
- {
- return $ "Multiplication of {value1} * {value2} is {value1 * value2}";
- }
- static void Main(string[] args) {
- string multiplication = Multiplication(10, 10);
- Console.WriteLine(multiplication);
- Console.ReadLine();
- }
- private static int Substract(int value1, int value2) {
- return value1 - value2;
- }
- Console.WriteLine($ "substraction of 7-5 is {Substract(7,5)}");

Join the conversation! Your thoughts help the community grow.