multiple line strings in C Sharp

Posted by – July 19, 2007

Today I found something that made my day. I have always hated that you can’t have strings span multiple lines of code in ASP.NET. For VB.NET this makes since, because there is no semi-colon at the end of statements. To get strings to span multiple lines in VB.NET, you can add an ampersand + space + underscore to the end of each line, like so:

dim sample as string = "notice how " & _
"the string is on multiple lines!" & _
"just make sure you put double quotes on the" & _
"beginning and end of each line"

This works for VB.NET, but not so for C#.NET. I have tried changing the ampersand to a plus sign (c sharp’s character to concatenate strings) but this didn’t work. I had assumed it was impossible, until I came across a solution today. Simply put an ‘at’ sign (@) before the string!

string sample = @"notice how
the string is on multiple lines!";

As you can see, in you don’t need to start and stop the string like you do in The only thing that is slightly tricky, is if you start concatenating strings. Then you need to add the @ symbol to every section of string that will be on multiple lines. For example:

string sample = @"this string
is on multiple lines" + someVariable + @" notice
how i had to use an 'at' symbol again, 
however i don't if the string section stays on one line, 
such as" + here + "... get it?";

Enjoy this ability to word-wrap you sql queries, or any other code strings which need to span multiple lines!

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=""> <strike> <strong>