Translate

All about String in C#

 String Interpolation in C#


In this post we will learn about "String Interpolation in C#". It is a technique of combining, formatting, and manipulating strings. This functionality was introduced in C# 6 version. By employing string interpolation, we can incorporate objects and expressions into the string interpolation process.

Important point is format of string interpolation begins with a ‘$’ symbol and expressions or string variables are enclosed within a brace {} using the subsequent format.

Syntax

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

Details of above Syntax

  • InterpolatedExpression: It is the expression that produces a formatted result.
  • Alignment: This value defines the minimum number of characters in the string representation of the result. If it is positive, then string representation is right-aligned and if negative, it will be left-aligned. 
  • FormatString: It is a format string that is supported by the type of the expression result.

Interpolation Sample Code

 static void Main(string[] args)
        {
            string name = "Code config";
            string finalValue = $"Welcome to {name} !";
            Console.WriteLine(finalValue);
            Console.ReadLine();
        }

Output



One more example of Interpolation is given below.

  static void Main(string[] args)
        {
         
            string name = "Mukesh Kumar";
            string expertise = "Asp.net Core";
            int year = 2023;
            string hello = $"Name of student is {name}. \n" +
            $"His is expert in {expertise }  & current year is  {year}. ";
            Console.WriteLine(hello);
            Console.ReadLine();
        }

Output:



String Interpolation in C# with "FormatString"

        static void Main(string[] args)
        {
            DateTime date = new DateTime();
            date = DateTime.Now;
            Console.WriteLine($"Today's date is {date:dddd, MMMM dd, yyyy} ");
            Console.ReadLine();
        }



No comments:

Post a Comment

Popular Posts