find and solve || findandsolve.com
Please wait.....

String interpolation in C#

In the C# programming language string interpolation is a method of concatenating, manipulating, and manipulating strings which feature is available starting with C# 6.

String Interpolation is a feature that is used to embed any valid expression that returns a value into a string using the $ operator. The string which is prepended with the $ operator will call an interpolated string.

In c#, the String Interpolation is an extended version of the string.Format() feature to provide a more readable and convenient way to include formatted string expression results into a string literal.

For example, by using string.Format() method, you can insert the values in a string like {0}, {1}, etc. but by using String Interpolation, you can directly include any valid c# expression that returns a value in an interpolated string using braces like {name} or {expression}.


In the given example of using both string.Format() and string interpolation in c# programming language to include expression values inside of a string.


using System;
using System.Text.RegularExpressions;
namespace FindAndSolve
{
    public class Program
    {
       public static void Main(string[] args)
       {
        string str = "FindAndSolve";
  DateTime date = DateTime.Now;
  //Normal formatting
  string strFormat = string.Format("Hello {0}, Today is {1} and it's {2:HH:mm} now.", str, date.DayOfWeek, date);
  Console.WriteLine(strFormat);
  //String interpolation
  string strResult = $"Hello {str}, Today is {date.DayOfWeek} and it's {date:HH:mm} now.";
  Console.WriteLine(strResult);
  //Output: Hi Suresh, Today is Friday and it's 05:38 now.
  Console.ReadLine();
       }
    }
}


Output


Hello FindAndSolve, Today is Monday and it's 13:51 now.

Hello FindAndSolve, Today is Monday and it's 13:51 now.


C# String Interpolation Structure


In c# programming language, to identify a string literal as an interpolated string, you need to prepend it with $ symbol, and there should not have any whitespace between the $ symbol and the double quote " that starts a string literal.

In the following is the structure of interpolated string with required expressions in c#.

{<interpolatedExpression>[,<alignment>][:<format_string>]}


Here the elements in square brackets [] are optional. The alignment and format_string elements are useful to format and adjust the alignment of the interpolated string based on your requirements.


In the following table lists, the details about each element interpolated strings in c# programming language.


ElementDescription
interpolatedExpressionThe expression that produces a result and it will be included in the interpolated string with braces {}

alignment a constant expression that is used to specify an alignment for expression result using comma(,).  if negative, it's left-aligned. If the alignment value is positive, then the formatted expression result is right-aligned
formatStringA format string that is supported by the type of expression result. To format the given expression, you can define formatString with interpolated expression using the colon (":").


In the following example, use optional formatting components in the interpolated string.


using System;
namespace FindAndSolve
{
    public class Program
    {
        public static void Main(string[] args)
        {
            double x = 11.21;
            double y = 4.23;
            const int ealign = 8;
            Console.WriteLine($"{x} + {y} = {x + y}");
            Console.WriteLine($"Sum with Format = {x + y,ealign:F2}");
            Console.ReadLine();
        }
    }
}


Output

11.21 + 4.23 = 15.440000000000001

Sum with Format = 15.44


C# String Interpolation Example


using System;
namespace FindAndSolve
{
    public class Program
    {
        public static void Main(string[] args)
        {
            string name = "FindAndSolve";
            DateTime date = DateTime.Now;
            double x = 11.78745;
            double y = 4.07878592;
            const int ealign = 8;
            Console.WriteLine($"Sum of {x} + {y} = {x + y}");
            Console.WriteLine($"Right Align with Format = {x + y,ealign:F2}");
            Console.WriteLine($"Left Align with Format = {x + y,-10:F4}");
            string strIntr = $"Hi {name}, Today is {date.DayOfWeek} and it's {date:HH:mm} now.";
            Console.WriteLine(strIntr);
            Console.ReadLine();
        }
    }
}


Output

Sum of 11.78745 + 4.07878592 = 15.86623592

Right Align with Format = 15.87

Left Align with Format = 15.8662

Hi FindAndSolve, Today is Monday and it's 19:58 now.



C# Multiline String Interpolation


In c# programming language, the String Interpolation will support multiline or verbatim interpolated string, which starts with the ‘@’ character. To implement the verbatim interpolated string, the string must start with $ character followed by @ character.

using System;
namespace FindAndSolve
{
    public class Program
    {
        public static void Main(string[] args)
        {
                string name = "FindAndSolve";
                string address = "Kathmandu";
                DateTime date = DateTime.Now;
                string msg = [email protected]"Hi {name}, Today is {date.DayOfWeek}
                and it's {date:HH:mm}Time Welcome to Find And Solve
                Your location is {address}";
                Console.WriteLine(msg);
                Console.ReadLine();
        }
    }
}


Output

Hi FindAndSolve, Today is Monday

and it's 20:04Time Welcome to Find And Solve

Your location is Kathmandu


If we observe the given example, you implemented a multiline interpolated string using $ character and it is followed by @ character.


C# String Interpolation with Ternary Operator (?:)


In c# programming language, you can use conditional ternary (?:) operator in interpolated expressions by enclosing it in parenthesis {} because in string interpolation, the character colon (“:”) is used to define the format for interpolation expression.

In the given example of using conditional ternary (?:) operator in c# string interpolated expression


using System;
namespace FindAndSolve
{
    public class Program
    {
        public static void Main(string[] args)
        {
            string name = "FindAndSolve";
            string msg = [email protected]"Hello , Welcome {(name == "FindAndSolve" ? "Design" : "Programming")}";
            Console.WriteLine(msg);
            Console.ReadLine();
        }
    }
}


Output

Hello, Welcome Design


C# String Interpolation Performance


In the c# programming language, the string interpolation performance is almost the same as String.Format() method. There is a tiny bit of overhead for the string interpolation in c# due to expressions embedding in the string, but that is very, very small.

From a performance point of view, both string interpolation and string.Format() are not suggestible. Instead, we can use StringBuilder. So you can use string interpolation in the c# programming language to include valid expressions within the string based on our requirements.