In C++, I can do this:
cout << "Line 1\nLine 2\n";
In Java, I can do this:
System.out.printf("Line 1%nLine 2%n");
In C#, do I really need to do one of these cumbersome things:
Console.WriteLine("Line 1");
Console.WriteLine("Line 2");
or
Console.Write("Line 1{0}Line 2{0}", Environment.NewLine);
or is there a more concise way, which is not platform-specific?
\r is carriage return, and \n is line feed. On "old" printers, \r sent the print head back to the start of the line, and \n advanced the paper by one line. Both were therefore necessary to start printing on the next line.
By using: \n – It prints new line. By using: \x0A or \xA (ASCII literal of \n) – It prints new line.
\r\n (windows - Environment. Newline) or \n (Unix) should work...
It's actually a backslash: "\n". It means a newline, like when you press the return or enter key. If you don't include the \n, the next print statement will continue on the same line. 9.
No, there is no concise, platform-agnostic, built-in newline placeholder in C#.
As a workaround, you could create an extension method for Environment.NewLine
public static class StringExtensions()
{
public static string NL(this string item)
{
return item += Environment.NewLine;
}
}
Now you can use NL
(picked because of brevity)
Console.Write("Hello".NL());
Console.Write("World".NL());
writes out:
Hello
World
You could also make an extension method that simply writes out something to the console.
public static void cout(this string item)
{
Console.WriteLine(item);
//Or Console.Write(item + Environment.NewLine);
}
And then:
"Hello".cout();
This should work:
Console.Write("Line 1\r\nLine 2");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With