I am wondering what is the \"best practice\" to break long strings in C# source code. Is this string
\"string1\"+
\"string2\"+
\"string3\"
con
How about the following extension method (which is inspired by common-tags oneLine method)...
using System;
using System.Text.RegularExpressions;
using static System.Text.RegularExpressions.RegexOptions;
namespace My.Name.Space
{
public static class StringHelper
{
public static string AsOneLine(this string text, string separator = " ")
{
return new Regex(@"(?:\n(?:\s*))+").Replace(text, separator).Trim();
}
}
}
...in combination with the verbatim string literal used as such:
var mySingleLineText = @"
If we wish to count lines of code, we should not regard them
as 'lines produced' but as 'lines spent'.
".AsOneLine();
Note that spaces "inside" the string are kept intact, for example:
// foo bar hello world.
var mySingleLineText = @"
foo bar
hello world.
".AsOneLine();
If you don't want newlines to be substituted with spaces, then pass "" as argument to the extension method:
// foobar
var mySingleLineText = @"
foo
bar
".AsOneLine("");
Please note: This form of string concatenation is conducted at run time due to the helper-method involved (in contrast to concatenation via the + operator occurring at compile time, as also stated in the accepted answer). So if performance is an issue, go with the +. If you are dealing with long phrases and readability and "ease of use" is the focus, then the approach suggested above may be worth considering.