C# Multi-line String Literals

  • From: Kerneels Roos <kerneels@xxxxxxxxx>
  • To: programmingblind <programmingblind@xxxxxxxxxxxxx>
  • Date: Wed, 11 Aug 2010 09:57:43 +0200

Hi List,

Three ways to do this, which one is best:

1.
StringBuilder sb = new StringBuilder();
sb.AppendLine("SELECT id ");
sb.AppendLine("FROM my_table ");
sb.AppendLine("WHERE id > 5");

2.
string myMultiLine = "SELECT id "
   + "FROM my_table"
   + "WHERE id >5";

3.
string myMultiLine = @"SELECT id
   FROM my_table
   WHERE id > 5";

Method 1 is the usual way, 2 introduces extra whitespace and lime breaks,
and 3 apparently does not result in slower code if the whole string is known
at compile time -- the compiler is smart enough to make it into one string
(see: http://jameskovacs.com/2007/02/12/multiline-strings-in-c/ ).

If you know that you are going to have to tweak the string and have a few
round trips to the query analyzer I would say that 2 would actually be best
since you only have to remove the first @" and last "; and the literal
string will run. Once you know the string is perfect I would say method 3 is
the best since it looks like it might be faster than method 1 and does not
have the extra, maybe unwanted additional whitespace and new line chars that
method 2 introduces.

What do you guys think?

Regards,

-- 
Kerneels Roos
Cell/SMS: +27 (0)82 309 1998
Skype: cornelis.roos

The early bird may get the worm, but the second mouse gets the cheese!

Other related posts: