Page 193 - CSharp/C#
P. 193

Expressions




        With string interpolation, expressions within curly braces {} can also be evaluated. The result will
        be inserted at the corresponding location within the string. For example, to calculate the maximum
        of foo and bar and insert it, use Math.Max within the curly braces:


         Console.WriteLine($"And the greater one is: { Math.Max(foo, bar) }");


        Output:

              And the greater one is: 42


        Note: Any leading or trailing whitespace (including space, tab and CRLF/newline) between the
        curly brace and the expression is completely ignored and not included in the output


        View Demo

        As another example, variables can be formatted as a currency:


         Console.WriteLine($"Foo formatted as a currency to 4 decimal places: {foo:c4}");


        Output:

              Foo formatted as a currency to 4 decimal places: $34.0000


        View Demo


        Or they can be formatted as dates:


         Console.WriteLine($"Today is: {DateTime.Today:dddd, MMMM dd - yyyy}");


        Output:

              Today is: Monday, July, 20 - 2015

        View Demo


        Statements with a Conditional (Ternary) Operator can also be evaluated within the interpolation.
        However, these must be wrapped in parentheses, since the colon is otherwise used to indicate
        formatting as shown above:


         Console.WriteLine($"{(foo > bar ? "Foo is larger than bar!" : "Bar is larger than foo!")}");


        Output:


              Bar is larger than foo!

        View Demo



        https://riptutorial.com/                                                                             139
   188   189   190   191   192   193   194   195   196   197   198