C# 6.0 Feature: String Interpolation



 String Interpolation


    In c# 6 a new feature for string manipulation called string interpolation by using '$' sign.
    Now you can directly write arguments in placeholders inside a string without
    worrying about numerical markers({0}).
    you can use string.Format method for formatting the string from previous version.

   See the below example:

   Before C#6
  
    using System;
    using System.Collections.Generic;
    using static System.Console;

    namespace NewInCSharp6

    {
        class Program
        {
            private static void Main(string[] args)
            {
                string RoadName = "M G Road";
                string PersonName = "Mahatama Gandhi";

                WriteLine("{0} is based on  {1} name.", RoadName, PersonName);


                ReadLine();

            }
        }
    } 

   After C#6

    using System;

    using System.Collections.Generic;
    using static System.Console;

    namespace NewInCSharp6

    {
        class Program
        {
            private static void Main(string[] args)
            {
                string RoadName = "M G Road";
                string PersonName = "Mahatama Gandhi";

                WriteLine($"{RoadName} is based on  {PersonName} name.");


                ReadLine();

            }
        }
    }

You can clearly see here you don't have to provide numerical marker and then string name in sequence order.   






You can even do formatting and Conditional check using '$'.Here you can see I am using ternary operator.

using System;
using System.Collections.Generic;
using static System.Console;

namespace NewInCSharp6

{
    class Program
    {
        private static void Main(string[] args)
        {
            string PersonName = "Peter Hensen";
            double Salary = 10000;

            WriteLine($"{PersonName}'s salary is {Salary}");            


            WriteLine($"This {PersonName} is getting { (Salary >= 1000 ? "Above average Salary." : "Below average salary.")}");

            ReadLine();
        }
    }
}











                                                                                                     Next :Dictionary Initializers
C# 6.0 Feature: String Interpolation C# 6.0 Feature: String Interpolation Reviewed by kamal kumar das on November 24, 2016 Rating: 5

No comments:

ads 728x90 B
Powered by Blogger.