In C#, you need strings often. Less often, you need a long string, but it still happens. So here’s a nice thing to know. You can split them over multiple lines without need the + operator and an Environment.NewLine call.

What you need is a verbatim string literal. Those start with an @:

@"c:\Docs\Source\a.txt"  // rather than "c:\\Docs\\Source\\a.txt"

But the extra nice thing is they can span multiple lines, making them easier to read:

@"Hello
  This is text on a new line.
  Bye!";

But what if you need to add some variable text to this string? Since C# 6 we can use string interpolation, combined with our verbatim string literal:

var name = "Peter";
$@"Hello {name},
   How are you?
   Bye!";

This works perfectly and gives us very readable code.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.