Writing a long string in multiple lines – c#

Writing a big string will always produce scrollbars in the editor. So it’s better to split it to multiple lines which is more easy to read. This post discusses the various methods that can be used to split big lines into multiple lines.

Check this big line.

string BigLine = "bla bla  bla bla  bla bla  bla bla  
bla bla  bla bla  bla bla  bla bla ";

Writing a string as shown above will produce error. This can be rewritten like

string BigLine = @"bla bla  bla bla  bla bla  bla bla  
bla bla  bla bla  bla bla  bla bla ";

Or

string</font> BigLine = "bla bla  bla bla  bla bla  bla bla " +
"bla bla  bla bla  bla bla  bla bla ";

I always prefer the second one. Because first one will not move the next line to the starting of first line. And more over it won’t be possible to write first method for the following type of string.

string BigLine = @"bla bla  bla bla  bla bla  bla bla  
bla bla  bla bla  bla bla\"test\"  bla bla ";

In this I am escaping " by specifying \. But .NET editor will produce an error.

Advertisements

10 thoughts on “Writing a long string in multiple lines – c#

  1. string BigLine = @”bla bla bla bla bla bla bla bla

    bla bla bla bla bla bla\”test\” bla bla “;

    You can escape ” by using “” (2 of them)

  2. Hi Navaneeth,

    Thanks for ur this article,
    But I want to split a long string into multiple line because I want to Print them. As we know the wrapping cannot be done in Printing.

  3. what can i do when one of the line is something like this

    “blaa= blaa.replace(‘/[\(\)\-\ ]/g’, ”);”+

    i got unrecognized escape sequence

  4. Ok,I got it…
    Just replace “+” with “& _”

    As in,

    Dim BigLine as string= “bla bla bla bla bla bla bla bla ” & _
    “bla bla bla bla bla bla bla bla “

  5. Be careful, not to split strings into multiple lines and use the “+” operator to append strings (especially if you do this task repeatedly). Appending strings are quite expensive – use StringBuilder instead.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s