C# Console.Write Example

Console screenshot

You want to write text to the console window, also called the command line window, and getting started with the Console can be confusing. Find out the difference between Console.Write and Console.WriteLine, and how you can choose which to use, and how to 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. If you are printing a string that already has a newline, you can use Console.Write for an entire line. Also, when you call WriteLine with no parameters, it writes a newline only.

This C# example program demonstrates the Console.Write method.

Program that uses Console.Write [C#]

using System;

class Program
{
    static void Main()
    {
	Console.Write("One ");     // <-- This writes the word only.
	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

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

Create strings

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 in the C# code. However, sometimes if you concatenate strings in your console program extensively before calling Console.Write, porting your code to another program will be more difficult. For this reason, I prefer to output strings as shown in the example.

Console.WriteLine

Programming tip

There are more tips on this site regarding using 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, so I feel both articles should be read together.

Console.WriteLine

Summary

.NET Framework information

Here we saw how you can use the Console.Write method in the C# language and .NET Framework. Specifically, we saw the difference between WriteLine and Write, and how you can use the two together for easily understandable code. Sometimes, using format strings is desirable, but they can also make the program less readable.

Console Programs
.NET