简体   繁体   中英

C# Console.Writeline and .Write differences

I'm just starting to learn C# and I was pointed to Microsoft own dev site for absolute beginner tutorials so I can start learning the proper syntax.

However in the first tutorial challenge they want you to make the console print out

This is the first line.
This is the second line.

I tried

Console.Write("This is the first line.");
Console.WriteLine("This is the second line.");

expecting that the second WriteLine would trigger a carriage return however it will not start a new line unless I put a

Console.Writeline(" ");

before the first WriteLine .

Why would Console.WriteLine not trigger the carriage return without first being preceded with a blank WriteLine ?

much thanks if your willing to help me understand.

        Console.Write("A");
        Console.Write("B");
        Console.WriteLine("C");
        Console.WriteLine("D");
        Console.WriteLine("E");
        Console.Write("F");

Code from above, would produce output like this:

在此处输入图像描述

That is because, as someone wrote in the comment, WriteLine puts a new line AFTER your output. So, after the Console.WriteLine, there will be a new row.

Console.WriteLine puts a line after the text you write. if you want to get your result just reverse them.

Console.WriteLine("This is the first line.");
Console.Write("This is the second line.");

Because the WriteLine command append the new line after the string inside the " " is writed.

If you add the \n at the end of the string in the Console.Write(), you have the same result.

The \n is a special character that is an alias for write new line command when putted inside a string text.

Console.WriteLine("text") = Console.Write("text\n")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM