TechCognition

Microsoft Visual Studio 2017 Promo Code
Microsoft Office 2016 Promo Code

Use Interpolated Strings Instead String.Format() in C# 6.0

C# 6.0 has new feature called Interpolated Strings to format the strings. It has several advantages as compared with String.Format(). In this article we discuss Interpolated strings advantages.

  • Interpolated strings provide more readable code and it also provides richer syntax for the expressions to produce the string

  • It enables the compiler to provided better static type checking, which decreases the chances of mistakes as compared with the String.Format() method

  • String.Format() works fine, but all substitutions are based on the numbers typed in the string as shown below.

 string sName = "Raj";

 string sProfession = "Software Developer";

 string sResult = String.Format("My Name is {0} and my role is {1}", sName, sProfession);

The above code works fine, and compiler produces correct results. But if the number of arguments not same as numbers we typed in the string as shown below.

string sName = "Raj";

 string sProfession = "Software Developer";

 

 string sResult = String.Format("My Name is {0} and my role is {1}", sName);

The above code produces the compile errors. It’s because we entered the two numbers (0 & 1) in the string, but we provided only one argument. So, by using String.Format() method we cannot predict whether our code produces correct results or exception until we run the code.

By using new Interpolated strings feature, we can avoid this type of issues. Interpolated strings have a prefix “$” before the string and instead of positional indices between {}} characters, we need to place actual C# expression as shown below.

string sName = "Raj";

string sProfession = "Software Developer";

 

 string sResult = $"My Name is {sName} and my role is {sProfession}";

Here we placed the two string variables (here sName & sProfession) in the resultant string, so there is no chance of getting wrong number of arguments exception. And also, by using Interpolated strings feature, code also becomes more readable

  • With String.Format(), it is very hard to verify that whether correct arguments are in correct order or not. But by using Interpolated strings, we can avoid this issue because we are directly placing the expressions instead of numeric indices

Let’s explore usage of Interpolated strings now. Not only variables, even you can place any C# expression by using interpolated strings. For example, we can display PI value from the Math library as shown below.

string sResult = $"The PI value is {Math.PI}";

Console.WriteLine(sResult);

Console.ReadLine();

Math.PI type is double, which is a value type. In order to coerce the double type to an Object, it will be boxed which impacts on significant impact on the performance. To avoid this convert double type to string by using ToString() extension method.

string sResult = $"The PI value is {Math.PI.ToString()}";

We can place conditional statements also through Interpolated strings. We need to place conditional statements within the parentheses.

bool isValid = true;

string sValid = "Valid", sInValid = "InValid";

string sResult = $"The expression is {(isValid ? sValid : sInValid)}";

With Interpolated strings, we can also place null coalescing operator in the expression.

string sName = null;

string sResult = $"The customer name is { sName ?? "missing"}";


Console.WriteLine(sResult);

Console.ReadLine();

Interpolated strings allow us to call methods also as expression.

class Program

{

        static void Main(string[] args)

        {

            string sResult = $"The customer name is { GetName() }";

 

            Console.WriteLine(sResult);

            Console.ReadLine();

        }

 

        private static string GetName()

        {

            return "Raj";

        }

}

Even we can call LINQ queries also within the interpolated strings.

string[] sNames = { "David", "Bob", "Raj", "Dave"};

string sResult = $"The number of names starts with the letter 'D' are { sNames.Where(n=>n.StartsWith("D")).Count().ToString() }";

 

Console.WriteLine(sResult);

Console.ReadLine();

Limitations of Interpolated strings:

  1. We can not use control flow statements like if/else, while as replacement strings within the interpolated string

  2. Interpolated strings just creates normal and we cannot use this feature to create parameterized SQL query.


Add comment

Loading

© Copyright 2018 www.techcognition.com | Sitemap