What is String Interpolation in C#? with example

String interpolation is a way to insert expressions into strings. It is a more readable and concise way to format strings than using the String.Format() method.

To use string interpolation, you enclose the expression in curly braces ({}). The expression can be any valid C# expression, including variables, constants, and functions.

For example, the following code uses string interpolation to print the current date and time:

using System;

namespace StringInterpolation
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime now = DateTime.Now;
            string message = $"The current date and time is {now}";
            Console.WriteLine(message);
        }
    }
}

The message variable is a string that contains the expression {now}. The {now} expression is evaluated at runtime and the result is substituted into the string. In this case, the result of the {now} expression is the current date and time.

The string interpolation syntax can also be used to format strings. For example, the following code uses string interpolation to format a number:

using System;

namespace StringInterpolation
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = 12345;
            string message = $"The number is {number:D4}";
            Console.WriteLine(message);
        }
    }
}

The message variable is a string that contains the expression {number:D4}. The {number:D4} expression formats the number number as a four-digit number with leading zeros.

String interpolation is a powerful tool that can be used to format and manipulate strings in a readable and concise way. It is a good choice for situations where you need to insert expressions into strings or format strings in a specific way.


 

Post a Comment

Previous Post Next Post