Re: C# Multi-line String Literals

  • From: "Jacques Bosch" <jfbosch@xxxxxxxxx>
  • To: <programmingblind@xxxxxxxxxxxxx>
  • Date: Wed, 11 Aug 2010 22:21:38 +0200

3rd option definitely best for readability. 
In terms of performance, for fixed number of concats, or anything less than 
multiple thousands for that matter, you will notice very negligible difference.
But what are you coding SQL in your strings for anyway. <G> Use and ORM.

  ----- Original Message ----- 
  From: Kerneels Roos 
  To: programmingblind 
  Sent: Wednesday, August 11, 2010 9:57 AM
  Subject: C# Multi-line String Literals


  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: