C# Console.WriteLine (Print)

Call the Console.WriteLine method. Print values like ints and strings to the screen.
Console. Above us the stars tell a story of great complexity. In C#, a console program communicates through text. It too delivers messages of importance.
Some methods. Console.WriteLine renders a line of text. Console.Write omits the newline. We can use format strings, and even use colors.Console Colors
WriteLine, print values. There are many overloads on Console.WriteLine. An overloaded method has the same name but accepts different parameters.

Types: The overload can have different types of parameters, different numbers of parameters, or both.


Print: We see the overloads for WriteLine. These methods print ints, strings and bools to the screen.

C# program that uses Console.WriteLine using System; class Program { static void Main() { // Write an int with Console.WriteLine. int valueInt = 4; Console.WriteLine(valueInt); // Write a string with the method. string valueString = "Your string"; Console.WriteLine(valueString); // Write a bool with the method. bool valueBool = false; Console.WriteLine(valueBool); } } Output 4 Your string False
Console, note. It is helpful to know that when you use the Console class, you do not need to create a new Console(). You need to add the "using System" line at the start.

Static: WriteLine is a static method on the Console type. You can specify System.Console.WriteLine() to reference the namespace directly.

Empty line. It is possible to use Console.WriteLine with no arguments. This will simply output a blank line to the Console window. This is an elegant way to output an empty line.Environment.NewLine
C# program that uses no arguments using System; class Program { static void Main() { Console.WriteLine("A"); Console.WriteLine(); // Empty line. Console.WriteLine("B"); } } Output A B
String, tip. In some programs, you will want to write several values on a single line to the Console. We can form a string using the "+" operator before passing it to Console.WriteLine.string.Concat
String, formats. A format string is often clearest. Here the first parameter is a literal that has N substitution places. The next N parameters are inserted in those places.string.Format

Tip: The commas in the format string are printed unchanged. Start counting at 0 for the format string substitution markers.

C# program that uses Console.WriteLine with format strings using System; class Program { static void Main() { string value1 = "Dot"; string value2 = "Net"; string value3 = "Perls"; Console.WriteLine("{0}, {1}, {2}", value1, value2, value3); } } Output Dot, Net, Perls
Same line. You can combine the Console.Write method with the Console.WriteLine method. Both methods can be used on the same line. Write does not append a newline to the end.Console.Write
Char arrays. This is an advanced feature of Console.WriteLine. It writes an entire char array to the screen. Char arrays are useful in optimization code and sometimes interop or DLL code.

Next: This example first writes the four chars in the array to the screen. It writes the middle two chars.

Char Array
C# program that uses Console.WriteLine with arrays using System; class Program { static void Main() { char[] array = new char[] { 'a', 'b', 'c', 'd' }; // // Write the entire char array on a new line. // Console.WriteLine(array); // // Write the middle 2 characters on a new line. // Console.WriteLine(array, 1, 2); } } Output abcd bc
ToString. When we pass an object to the Console.WriteLine method, it invokes the ToString override method on the class (if one exists). Here we see this happen with a Test class.ToString
C# program that uses ToString with Console.WriteLine using System; class Test { public override string ToString() { // Printed by Console.WriteLine. return "Test object string"; } } class Program { static void Main() { // Create class with ToString method. Test test = new Test(); // WriteLine calls to the ToString method. Console.WriteLine(test); } } Output Test object string
Using static System.Console. Suppose we want to avoid typing "Console" in our program to save time. We can add "using static System.Console" to the top.

And: We then just call WriteLine() instead of Console.WriteLine. This is syntactic sugar—the program's instructions are the same.

C# program that shows using static syntax using static System.Console; class Program { static void Main() { // We can just write WriteLine instead of Console.WriteLine. // ... This saves exactly 8 characters. WriteLine("Hello my friend!"); } } Output Hello my friend!
Title. Here we use a loop and simply set the Console.Title property to whatever the user typed into the console. You can change the title of the console window by entering text.

Tip: Console.Title allows us to change the console window title. We can use it to reduce the amount of text written to the screen.

C# program that uses Title property using System; class Program { static void Main() { while (true) { // Assign Console.Title property to string returned by ReadLine. Console.Title = Console.ReadLine(); } } }
CapsLock. This program prints the value returned by Console.CapsLock every one second. Try pressing the caps lock key. It will start printing True when the key is pressed.Sleep

Tip: If a program is requiring a password, you could print an error message if caps lock is pressed and the password is incorrect.

Tip 2: You could even add a separate "mode" in your program depending on whether caps lock is pressed.

C# program that uses CapsLock property using System; using System.Threading; class Program { static void Main() { while (true) { Thread.Sleep(1000); bool capsLock = Console.CapsLock; Console.WriteLine(capsLock); } } } Output False False True True True False True True
NumberLock. This program prints to the console every one second. As this program executes, you can press Num Lock and the output of the program will change.

Tip: You cannot set the value of the NumberLock property. If you do not want the key pressed, you must tell the user to press it again.

C# program that uses NumberLock using System; using System.Threading; class Program { static void Main() { while (true) { Console.WriteLine(Console.NumberLock); Thread.Sleep(1000); } } } Output False False True True False False
Height, width. With WindowWidth, we control the width of a window based on the number of text columns. Height changes the window size based on lines of text.

Tip: With WindowHeight and its companion property LargestWindowHeight, we gain control over a window's height.

C# program that sets height, width using System; class Program { static void Main() { // ... Width is the number of columns of text. Console.WindowWidth = 40; // ... Height is the number of lines of text. Console.WindowHeight = 10; // ... Say hello. Console.WriteLine("Hi"); } }
Console performance. In many simple console programs, the Console.WriteLine may be one of the biggest slowdowns. Here we time 100 lines written to the console.

Version 0: This version calls Console.WriteLine 100 times. Each line has a single char (not including a newline).

Version 1: This version uses StringBuilder.AppendLine to merge 100 lines into a single string, and then calls Console.WriteLine once.

Result: It is about 10 times faster to only call Console.WriteLine once. Combining strings before writing them is faster.

Tip: To run this benchmark, change the value of the "version" int from 0 to 1 (and back again).

C# program that times Console.WriteLine using System; using System.Diagnostics; using System.Text; class Program { static void Main() { int version = 0; var t1 = Stopwatch.StartNew(); if (version == 0) { // Version 0: write 100 separate lines. for (int i = 0; i < 100; i++) { Console.WriteLine("x"); } } else if (version == 1) { // Version 1: write 100 lines as a single string. StringBuilder temp = new StringBuilder(); for (int i = 0; i < 100; i++) { temp.AppendLine("x"); } Console.WriteLine(temp.ToString()); } // Results. Console.WriteLine("TIME FOR VERSION {0}: {1} ms", version, t1.ElapsedMilliseconds); } } Output TIME FOR VERSION 0: 35 ms TIME FOR VERSION 1: 3 ms
Colors. The world is full of colors. We can combine Console.Write and WriteLine with Console coloring. This can enhance a program's usability.
SetOut. With this method, we can use another type like a StreamWriter to write data to a console window. This can "glue" parts of a program together.SetOut
Read. Here we read in user input from the terminal window. When the user types in characters, you can read that instantly with ReadKey or when the Enter key is pressed, using ReadLine.ReadReadKeyReadLine
Arguments. It is useful to pass string arguments to your console programs. You can do this by creating a shortcut in Windows to the actual executable.Main args
GetCommandLineArgs. This method is part of the Environment type. With it we can fetch the command-line arguments where ever we are in the program logic.Environment.GetCommandLineArgs
Beep. Annoying beeps are occasionally useful in programs. We take a humorous look at the Beep method on the Console type. Please do not read this article.Beep
Console benchmarks. Here is a console program I use all the time. It is a benchmark program. So if you want to see if method 1 is 0.001% faster than method 2, this is a place to start.Benchmark
A review. Console.WriteLine is a useful method. At first, it may seem less interesting than others. But then we realize how many programs in C# can be written with just console output.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to
Dot Net Perls