In C#, what's the best way to spread a single-line string literal across multiple source lines?

Solution 1:

I would use a variation of your method:

string longString =
    "Lorem ipsum dolor sit amet, consectetur adipisicing " + 
    "elit, sed do eiusmod tempor incididunt ut labore et dolore magna " + 
    "aliqua. Ut enim ad minim veniam.";

Here I start the string on the line after the equals sign so that they all line up, and I also make sure the space occurs at the end of the line (again, for alignment purposes).

Solution 2:

If you want to keep the code as minimal as you can and be able to read it easily I would still go with a @ literal string. Plus its faster if you source is long and..

string verbatimLit = @" 
   __   __  
  /  `-'  \ 
 /_| N   |_\  Sometimes
   |  I  |    format in code
   |   N |    matters
   |_____|  
";

Then remove the newlines from the string in 1 line,

verbatimLit.Replace(Environment.NewLine, " ");

Solution 3:

Your original idea is probably the easiest way to have an embedded literal string in your code. The C# compiler merges literals concatenated with + - so it's essentially equivalent to a single really long string.

Another option, of course, is to externalize the string into a configuration file or a settings file. This would allow it to be both more easily readable and easier to change or localize. I personally avoid placing long lines of text directly into the code of an application unless they are very static and don't need localization - internal exception message text, and the like.

Solution 4:

For SQL queries or other long strings that have their own syntax, I'll sometimes do something like this:

        private const string QUERY = @"
SELECT *
FROM Table1 AS T1
INNER JOIN Table2 AS T2 ON T1.ID = T2.T1ID
WHERE T1.VALUE = @P1
GROUP BY T2.OTHERVALUE
";

This leaves the formatting of the string intact.

Solution 5:

Following Tj Kellie answer, in C# 6.0 you can easily have one instruction to perform concatenation and embedding of various information through string interpolation and also not having newlines in spite of defining the string on multiple lines.

A complex example involving all these can look like the following:

public int? BestTime { get; set; }
public int? WorstTime { get; set; }
public int? AvgTime { get; set; }
public int TimeoutReachedCount { get; set; }
public int AllRunCount { get; set; }

public string Str => $@"
   Ran {AllRunCount} times; 
   Reached timeout {TimeoutReachedCount} times; 
   Best time = {(BestTime.HasValue ? BestTime.ToString() : "N/A")}; 
   Worst time = {(WorstTime.HasValue ? WorstTime.ToString() : "N/A")}; 
   Average time = {(AvgTime.HasValue ? AvgTime.ToString() :"N/A")};"
       .Replace(Environment.NewLine, "");

Of course, extra care must be used to append blanks at the end of the lines to avoid words merging.