Interpolated Strings Over string.Format() in C#

We use string.Format() syntax to format the string in C#, but it has several disadvantages. String.Format() doesn’t show up any mistakes if it has until the content of the resultant string has been tested and validated. 

class Program
{
        static void Main(string[] args)
        {
            string str = "My Name is {0} and I am from {1}";
            string result = string.Format(str, "Raj", "US");
        }
}

As shown above, all the substitutions are based on numbers typed into the format string. Here compiler does not validate the numbers you entered in the format string matches number of arguments you passed onto string.Format() method. If you pass the wrong arguments, then you will get a run-time exception. Moreover, in case of a large number of arguments, it is very hard to verify whether you are passing arguments in the correct order or not, you have to run the code to verify it. 

We can resolve all the above issues with the new feature called Interpolated strings available from C# 6.0. Interpolated strings have a $ symbol as the prefix before the format string and instead of positional indices between { } characters we can place any C# expression like variables. 

string name = "Raj", country = "US";
string result = $"My Name is {name} and I am from {country}";

As shown above, we just placed the C# variables name and country for the interpolated string. If you observe here, with interpolated strings, we don’t use indices for string format that means we don’t get a wrong number of arguments exception at run-time. And, you can avoid placing the wrong argument at the wrong place by using interpolated strings. In interpolated string, we just place the C# expression which increases great readability of the code. 

If you want to use the conditional expression in the interpolated string, we need to place it within the parentheses as shown below. 

double salary = 10000.12;
bool round = true; 

string result = $"My Salary: {(round ? Math.Round(salary).ToString() : salary.ToString())} USD";

We can use null coalescing operator in interpolated string as below. 

string empId = null;
string result = $" {empId ?? "Employee Data Not Found"}";

We can also use Linq query in interpolated string like below. Here we are summing first two items from the list. 

List<int> list = new List<int>(); 

list.Add(100);
list.Add(200);
list.Add(300);
list.Add(400); 

string result = $"First two items sum: {list.Take(2).Sum().ToString()}";