Multi line strings in C#

Instead of writing

string query =
"select * " +
"from Customer " +
"where CustomerID = @customerID";

or

string xml =
"<Customers> " + Environment.NewLine +
"    <Customer> " + Environment.NewLine +
"        <ID value=\"12\"/> " + Environment.NewLine +
"    </Customer> " + Environment.NewLine +
"</Customers>";

one can write

string query =
"select *
from Customer
where CustomerID = @customerID";

or

string xml =
@"
<Customers>
    <Customer>
        <ID value='12'/>
    </Customer>
</Customers>
";

with just quotation marks in the beginning and end – not at every row.

Note how one can write apostrophes ( ‘ ) instead of quotation mark ( ” ) for the xml attributes.

The at sign ( @ ) is there to tell the parser that any back slashes ( \ ) should be treated like regular characters and not escape characters.  Very useful when handling files and folders on the Windows platform.  Not very useful in my example.

Also note that if you want an xml declaration <?xml version=’1.0′ encoding=’utf-8’ ?> it must be before any whitespace

string xml =
@"<?xml version='1.0' encoding='utf-8' ?>
<Customers>
    ...

In Vbnet one can write XML inline – like if it is a part of the language.

3 Responses to “Multi line strings in C#”

  1. Manuel says:

    I tried in a couple of machines using the C# editor in VS2010 this didn’t seem to work. Maybe I’m missing something?

  2. Manuel says:

    Using the C# editor with VS2010 this didn’t seem to work. Probably a plugin?

  3. selfelected says:

    Not a plugin, I got it through example code somewhere. Are you running Dotnet4?

Leave a Reply