Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concise way of outputting newlines in C#

Tags:

c#

.net

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?

like image 462
Klitos Kyriacou Avatar asked Feb 28 '11 16:02

Klitos Kyriacou


People also ask

What's the difference between \r and \n?

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

What does \n do in C sharp?

By using: \n – It prints new line. By using: \x0A or \xA (ASCII literal of \n) – It prints new line.

How do we specify a newline in AC string?

\r\n (windows - Environment. Newline) or \n (Unix) should work...

What does '/ N mean?

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.


2 Answers

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();
like image 197
George Stocker Avatar answered Sep 30 '22 08:09

George Stocker


This should work:

Console.Write("Line 1\r\nLine 2");
like image 33
ilivewithian Avatar answered Sep 30 '22 08:09

ilivewithian