Search code examples
c#c#-6.0string-interpolation

Long string interpolation lines in C#6 don't support Tab,CR and LF


I tried to use string interpolation $"" in C#6 with tabs

 var name="My Name";
 var text =$"\t\t{name}";

and it's working fine and tabs \t is resolved.

When trying to use Long string interpolation lines

      var name = "myname";
      var text = $@"\t\t{name}
                    tab and name  is in a Long string interpolation \r\n
       ";
    Console.WriteLine(text);

output

     \t\tmyname
                    tab and name  is in a Long string interpolation \r\n  

The tab \t ,\r and \n aren't resolved

So i had to use string.Format() to resolve this issue.

The question:

Is this a limitation in the Long string interpolation for not supporting \t \r \n in c#6 (even c#7)


Solution

  • You have the verbatim modifier @ in front of that string, so your tab characters will be un-escaped and treated as normal text. If you want to include them in the string, then you can either enclose the characters in curley brackets (since you're also using the $ string interpolation modifier) so they're treated as tabs (same with the carriage return and newline characters):

        var name = "myname";
        var text = $@"{"\t\t"}{name}
                tab and name  is in a Long string interpolation {"\r\n"}
    ";
        Console.WriteLine(text);
    

    Alternatively, since it's a verbatim string, you can just press Tab (or Enter) keys where you want those characters in the string.

    This string is the same as the one above:

        var text = $@"      {name}
                tab and name  is in a Long string interpolation 
    
    ";