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.
When finding yourself in question on how to do multiline strings, you might be better of using a Resources file.
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..
Then remove the newlines from the string in 1 line,
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:
Of course, extra care must be used to append blanks at the end of the lines to avoid words merging.
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.
I would use a variation of your method:
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).
For SQL queries or other long strings that have their own syntax, I'll sometimes do something like this:
This leaves the formatting of the string intact.