Home
C#
Console.Write Example
This page was last reviewed on Dec 21, 2022.
Dot Net Perls
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.
Console.WriteLine
Shows a console
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.
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.
Shows a console
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.
String 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"); } }
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.
string.Concat
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2024 Sam Allen.