Console.Write. This 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.
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.
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");
}
}X Y 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.