C# language feature:

  • String interpolation

applies to

  • formatting of strings

benefit

  • Allows writing of string formatting expressions using inline expressions instead of positional arguments. Improves code readability.

how to use

  • Prefix interpolated string with $ and replace position index with interpolated expression. Argument list is no longer needed.

note

  • Any valid C# expression is allowed inside the { } characters in an interpolated string which includes and is not limited to computations, conditionals, method calls, and LINQ queries. Interpolated string syntax is $"<text> {<interpolated-expression> [,<field-width>] [:<format-string>] } <text> ..."

example:

        class String_interpolation_Example
        {
            public void Use_of_String_interpolation()
            {
                var name = "Jeff";
                Console.WriteLine($"Hello, {name}!");   // note $ prefix used to denote embedded inline code.
                // old way i.e. composite string formatting
                Console.WriteLine("Hello, {0}!", name);  // note the argument 'name' is not needed for string interpolation
            }

        }