C# Console.Write

Console screenshot

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. We decide which one to choose. We even use them together.

Example

Note

The Console.Write method requires the System namespace to be included at the top to get the fully qualified name. 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.

Program that uses Console.Write: C#

using System;

class Program
{
    static void Main()
    {
	Console.Write("One ");     // <-- This writes the word.
	Console.Write("Two ");     // <-- This is on the same line.
	Console.Write("Three");    // <-- Also on the same line.
	Console.WriteLine();       // <-- This writes a newline.

	Console.WriteLine("Four"); // <-- This is on the next line.
    }
}

Output

One Two Three
Four

The Console.Write method is ideal for when you do not know what you need to output in advance. You could use a StringBuilder for this scenario. But the Write method provides immediate output and requires less code to use.

StringBuilder

Discussion

String type

In most console programs, the actual time required for outputting the text to the screen, mainly in the lower levels of Windows, is far greater than string concatenations. Windows must do many things to display text.

Note:If you concatenate strings before calling Console.Write, porting your code to another program may be more difficult.

string.Concat

WriteLine

Programming tip

We also cover the Console.WriteLine method, which is probably more common in most console-based applications written in the C# language. Knowing how to use Console.Write and Console.WriteLine together was not intuitive to me.

Console.WriteLine

Summary

Framework: NET

We used the Console.Write method in the C# language and .NET Framework. We saw the difference between WriteLine and Write. We learned how to use the two together for easily understandable code.

And:Sometimes using format strings is desirable, but they can also make the program less readable.

string.Format

C#: .NET: Console