62

Suppose that you have a lengthy string (> 80 characters) that you want to spread across multiple source lines, but don't want to include any newline characters.

One option is to concatenate substrings:

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";

Is there a better way, or is this the best option?

Edit: By "best", I mean easiest for the coder to read, write, and edit. For example, if you did want newlines, it's very easy to look at:

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";

I am wondering if there is something just as clean when you don't want newlines.

7 Answers 7

75

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).

6
  • 1
    I like this approach the best. Jan 2, 2010 at 2:40
  • 34
    It's also nice that the C# compiler merges such string literals at compilation time, so there's no runtime cost associated with this.
    – LBushkin
    Jan 2, 2010 at 2:44
  • Have you ever tried this for splitting up even a few paragraphs of source though? It's tedious work compared to a @ string to convert.
    – Tj Kellie
    Jan 28, 2014 at 19:18
  • This is all I wanted!
    – Marj
    Aug 8, 2017 at 20:29
  • @EricLippert, I'm making an assumption that the compiler still makes these optimisations when string interpolation is used.
    – Jodrell
    Jul 31, 2019 at 9:55
43

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, " ");
2
  • 2
    Nice approach. Though wouldn't you want to replace each newline with a space? Otherwise, contents<newline>here will become contentshere instead of contents here. (Or, one could prepend each line following the first with a space.)
    – DavidRR
    Jan 23, 2014 at 15:56
  • ATTENTION This code is subtly buggy: the Environment.NewLine depends by the runtime environment while che NewLine convention used depends by the compile-time environment. Jan 20, 2022 at 15:36
14

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.

8

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.

4

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.

0

When finding yourself in question on how to do multiline strings, you might be better of using a Resources file.

2
  • 3
    Please show an example of using such strings in a resource file. Jan 2, 2010 at 3:47
  • Resource files are great but you are looking at IO and storage then. Can be a pain on cross platform apps but I try and use resource files if reasonable to do so.
    – Craig.C
    Jan 6, 2021 at 20:30
-4

You could use multiple consts and then combine them into one big string:

const string part1 = "part 1";
const string part2 = "part 2";
const string part3 = "part 3";
string bigString = part1 + part2 + part3;

The compiler will "fold" these constants into one big string anyway, so there is no runtime cost at all to this technique as compared to your original code sample.

There are a number of advantages to this approach:

  1. The substrings can be easily reused in other parts of the application.
  2. The substrings can be defined in multiple files or types, if desired.
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.