How to insert newline in string literal?
If you want a const string that contains Environment.NewLine in it you can do something like this:
const string stringWithNewLine =
@"first line
second line
third line";
EDIT
Since this is in a const string it is done in compile time therefore it is the compiler's interpretation of a newline. I can't seem to find a reference explaining this behavior but, I can prove it works as intended. I compiled this code on both Windows and Ubuntu (with Mono) then disassembled and these are the results:
As you can see, in Windows newlines are interpreted as \r\n and on Ubuntu as \n
var sb = new StringBuilder();
sb.Append(first);
sb.AppendLine(); // which is equal to Append(Environment.NewLine);
sb.Append(second);
return sb.ToString();
One more way of convenient placement of Environment.NewLine in format string. The idea is to create string extension method that formats string as usual but also replaces {nl} in text with Environment.NewLine
Usage
" X={0} {nl} Y={1}{nl} X+Y={2}".FormatIt(1, 2, 1+2);
gives:
X=1
Y=2
X+Y=3
Code
///<summary>
/// Use "string".FormatIt(...) instead of string.Format("string, ...)
/// Use {nl} in text to insert Environment.NewLine
///</summary>
///<exception cref="ArgumentNullException">If format is null</exception>
[StringFormatMethod("format")]
public static string FormatIt(this string format, params object[] args)
{
if (format == null) throw new ArgumentNullException("format");
return string.Format(format.Replace("{nl}", Environment.NewLine), args);
}
Note
If you want ReSharper to highlight your parameters, add attribute to the method above
[StringFormatMethod("format")]
This implementation is obviously less efficient than just String.Format
Maybe one, who interested in this question would be interested in the next question too: Named string formatting in C#
Well, simple options are:
string.Format
:string x = string.Format("first line{0}second line", Environment.NewLine);
String concatenation:
string x = "first line" + Environment.NewLine + "second line";
String interpolation (in C#6 and above):
string x = $"first line{Environment.NewLine}second line";
You could also use \n everywhere, and replace:
string x = "first line\nsecond line\nthird line".Replace("\n",
Environment.NewLine);
Note that you can't make this a string constant, because the value of Environment.NewLine
will only be available at execution time.