Page 194 - CSharp/C#
P. 194

Conditional expressions and format specifiers can be mixed:


         Console.WriteLine($"Environment: {(Environment.Is64BitProcess ? 64 : 32):00'-bit'} process");


        Output:


              Environment: 32-bit process




        Escape sequences




        Escaping backslash (\) and quote (") characters works exactly the same in interpolated strings as
        in non-interpolated strings, for both verbatim and non-verbatim string literals:


         Console.WriteLine($"Foo is: {foo}. In a non-verbatim string, we need to escape \" and \\ with
         backslashes.");
         Console.WriteLine($@"Foo is: {foo}. In a verbatim string, we need to escape "" with an extra
         quote, but we don't need to escape \");


        Output:


              Foo is 34. In a non-verbatim string, we need to escape " and \ with backslashes.
              Foo is 34. In a verbatim string, we need to escape " with an extra quote, but we don't
              need to escape \

        To include a curly brace { or } in an interpolated string, use two curly braces {{ or }}:


         $"{{foo}} is: {foo}"


        Output:


              {foo} is: 34

        View Demo




        FormattableString type




        The type of a $"..." string interpolation expression is not always a simple string. The compiler
        decides which type to assign depending on the context:


         string s = $"hello, {name}";
         System.FormattableString s = $"Hello, {name}";
         System.IFormattable s = $"Hello, {name}";


        This is also the order of type preference when the compiler needs to choose which overloaded
        method is going to be called.



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