String Interpolation in C#

String interpolation has been around since C# version 6, so it is not exactly new, but even so, I sometimes encounter developers who are not familiar with the format.

In this article, we will explore some of the features of string interpolation; the good, the bad and the ugly.


Before the introduction of string interpolation, you only had two choices when it came to compiling a string with variable data. You either had to concatenate the string and the variables together, or you had to use composite formatting, as shown below.



 class Program
  {
    static void Main(string[] args)
    {
      string name = "Clark Kent";
      DateTime now = DateTime.Now;

      // Concatenate
      var concatMsg = "Hi there, " + name + ". Today is " + now.DayOfWeek + " and the time is " + now.ToString("HH:mm") + ".";

      Console.WriteLine(concatMsg);

      // Composite
      var compositeMsg = string.Format("Hi there, {0}. Today is {1} and the time is {2:HH:mm}.", name, now.DayOfWeek, now);
      Console.WriteLine(compositeMsg);
    }
  }

Both of these methods are perfectly acceptable on short strings, but things become a bit messy when you start dealing with more variables. Imagine you are dealing with a string containing 20 variables. With concatenation, it will be readable, but all those plus signs are enough to make me nauseous. Composite formatting, on the other hand, becomes very difficult to read when you are dealing with long strings with lots of variables.


I reckon, if concatenation and composite formatting had a child, it would be named interpolation. It is the best of both.


With interpolation, you get the readability of concatenation, with the ease of use of composite formatting. Let's extend our previous example by adding an interpolated string.



class Program
  {
    static void Main(string[] args)
    {
      string name = "Clark Kent";
      DateTime now = DateTime.Now;

      // Concatenate
      var concatMsg = "Hi there, " + name + ". Today is " + now.DayOfWeek + " and the time is " + now.ToString("HH:mm") + ".";

      Console.WriteLine(concatMsg);

      // Composite
      var compositeMsg = string.Format("Hi there, {0}. Today is {1} and the time is {2:HH:mm}.", name, now.DayOfWeek, now);
      Console.WriteLine(compositeMsg);

      // Interpolation
      var interpolatedMsg = $"Hi there, {name}. Today is {now.DayOfWeek} and the time is {now:HH:mm}.";
      Console.WriteLine(interpolatedMsg);
    }
  }


As you can see, interpolation is not only easier to read, but also shorter to type.


The basic structure of an interpolation expression is as follows, where the "alignment" and "formatString" elements are optional:


{<interpolationExpression>[,<alignment>][:<formatString>]}


The alignment element allows you to specify the alignment of the expression result. If the value is negative, the expression result will be left-aligned; if the value is positive, the expression result will be right-aligned.



class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine($"|{"I am left",-20}|{"I am right",20}|");
    }
  }


The alignment option is especially useful when generating text-based reports.


The "formatString" option allows us to format strings during interpolation. For instance, if we want to format the value of Pi to 3 decimals, we can use the following code.



class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine($"Left-aligned");
      Console.WriteLine($"=================================");
      Console.WriteLine($"{Math.PI, 0} - Default Formatting - Left Aligned");
      Console.WriteLine($"{Math.PI, 0:F3} - Decimal Formatting - Left Aligned");

      Console.WriteLine();
      Console.WriteLine($"Right-aligned");
      Console.WriteLine($"=================================");
      Console.WriteLine($"{Math.PI, 20} - Default Formatting - Right Aligned");
      Console.WriteLine($"{Math.PI, 20:F3} - Decimal Formatting - Right Aligned");
    }
  }


What about special characters? Well, you need to be aware of the following:

  • If you want to include braces in your text, you will need to escape the braces with additional braces in the following manner {{}}. Doing this will produce a single set of braces in your text.
  •  To include quotation marks in your text, you need to escape each of them with a back-slash such as \".

The following code demonstrates how to escape these characters and their resulting strings.



class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine($"Here we want to show braces like this {{}}.");

      Console.WriteLine();

      Console.WriteLine($"Now we want some quotation marks like this \"\"\"\".");

      Console.WriteLine();

      Console.Write($"We can also use some standard end of line escapes \r\nlike the ones which created a second line.\r\n");

      Console.WriteLine();
      
      Console.Write($"What about back-slashes?  Well, we can do those too \\\\.");

      Console.WriteLine();

    }
  }


You may have noticed that the example code includes additional special characters. Well, these are standard when working with strings, and can be escaped in the usual manner.


If you want a more hands-on experience with string interpolation, have a look at the following tutorial from Microsoft:


https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/exploration/interpolated-strings 

Comments

Popular posts from this blog

.NET Core JWT Authentication