C# Console.Write ExampleInvoke the Console.Write method. Write appends but does not use a newline.
Console.Write puts text on the console window. Getting started with the Console can be confusing. We learn the difference between Console.Write and Console.WriteLine.
Padding notes. We can place whitespace after a Console.Write call to add padding and even justify strings. The PadRight method can be used here.
Example. First, be sure to remember to include the System namespace at the top. We see that the Write method does not append a newline to the end of the console.
Using System
Also If you are printing a string that already has a newline, you can use Console.Write for an entire line.
And When you call WriteLine with no parameters, it only writes a newline. It always writes a newline.
using System; class Program { static void Main() { Console.Write("One "); Console.Write("Two "); Console.Write("Three"); Console.WriteLine(); Console.WriteLine("Four"); } }
One Two Three Four
Padding example. The Console.Write method is ideal when we do not yet know the exact output. Here we use PadRight() to add padding onto strings as we Write them.
PadRight, PadLeft
using System; class Program { static void Main() { // Use PadRight to create columns with Console.Write. Console.Write("X".PadRight(5)); Console.Write("Y".PadRight(5)); Console.WriteLine("END"); } }
Discussion. In most console programs, the actual time required for outputting the text to the screen, is far greater than string concatenations.
Note If you concatenate strings before calling Console.Write, porting your code to another program may be more difficult.
Summary. We used the Console.Write method. We saw the difference between WriteLine and Write. We learned how to use the two together for easily understandable code.
© 2007-2022 sam allen.
see site info on the changelog.