String Interpolation

We have all used the good old reliable String.Format() method, but recently I ran across the newer sleeker way of handling strings in C#. It is called "String Interpolation" and it is definitely a shortcut to constructing strings. Although string interpolation is not a new thing in itself, this implementation in C# is rather nice, once you are used to it.

 

Older Method with String.Format()

public static void OldMethod()
{
            string firstName = "John";
            string lastName = "Doe";

            var formattedString = string.Format("Hello World, My Name is {0}, {1}", firstName, lastName);
            Console.WriteLine(formattedString);
}

 

New Method using string interpolation:    

public static void NewMethod()
{
            string firstName = "John";
            string lastName = "Doe";

            var formattedString = $"Hello World, My Name is {firstName}, {lastName}";
            Console.WriteLine(formattedString);
}

 

There is nothing wrong with the older method and personally I still sort of like it.  Pick the best method for your development style and keep on coding.

Add comment

Loading