Console
Console
programs communicate through text. Many features are available in C#: Console.WriteLine
renders a line of text. Console.ReadLine
gets user input.
For console output, we can use format strings and colors. A red warning message can be written. These features are helpful when developing with the "dotnet" command line program.
WriteLine
There are many overloads on Console.WriteLine
. An overloaded method has the same name but accepts different parameters.
int
to the screen with Console.WriteLine
. A newline comes after the int
.string
variable to WriteLine
to print the string
. This is another overload of the WriteLine
static
method.bool
, can also be passed to Console.WriteLine
. Even objects can be used.using System; // Part 1: write an int with Console.WriteLine. int valueInt = 4; Console.WriteLine(valueInt); // Part 2: write a string with the method. string valueString = "Your string"; Console.WriteLine(valueString); // Part 3: write a bool with the method. bool valueBool = false; Console.WriteLine(valueBool);4 Your string False
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.
using System; class Program { static void Main() { Console.WriteLine("A"); Console.WriteLine(); // Empty line. Console.WriteLine("B"); } }A B
Console
, Concat
In some programs, we 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
temporary for the concatenation, but overall this rarely impacts performance.using System; class Program { static void Main() { string name = "USER"; int id = 100; // A string is created before WriteLine is called. Console.WriteLine(name + ": " + id); } }USER: 100
Console
, WriteWe 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.
string
temporary is created to write the 3 parts, but 3 Console
calls may be slower overall than a single string
concatenation.using System; class Program { static void Main() { string name = "USER"; int id = 100; // Write 3 parts to the same line. Console.Write(name); Console.Write(": "); Console.WriteLine(id); } }USER: 100
String
, formatsA 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
are printed unchanged. Start counting at 0 for the format string
substitution markers.using System; class Program { static void Main() { string value1 = "Dot"; string value2 = "Net"; string value3 = "Perls"; Console.WriteLine("{0}, {1}, {2}", value1, value2, value3); } }Dot, Net, Perls
Char
arraysThis 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.
using System; class Program { static void Main() { char[] array = new char[] { 'a', 'b', 'c', 'd' }; // ... Write the entire char array on a line. Console.WriteLine(array); // ... Write the middle 2 characters on a line. Console.WriteLine(array, 1, 2); } }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
.
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); } }Test object string
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.
WriteLine()
instead of Console.WriteLine
. This is syntactic sugar—the program's instructions are the same.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!"); } }Hello my friend!
Here we use a loop and set the Console.Title
property to whatever the user typed into the console. We can change the title of the console window by entering text.
Console.Title
allows us to change the console window title. We can use it to reduce the amount of text written to the screen.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 1 second. Try pressing the caps lock key. It will start printing True when the key is pressed.
using System; using System.Threading; class Program { static void Main() { while (true) { Thread.Sleep(1000); bool capsLock = Console.CapsLock; Console.WriteLine(capsLock); } } }False False True True True False True True
NumberLock
This program prints to the console every 1 second. As it executes, we can press Num Lock and the output of the program will change.
NumberLock
property. If we do not want the key pressed, we must tell the user to press it again.using System; using System.Threading; class Program { static void Main() { while (true) { Console.WriteLine(Console.NumberLock); Thread.Sleep(1000); } } }False False True True False False
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.
WindowHeight
and its companion property LargestWindowHeight
, we gain control over a window's height.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"); } }
In many simple console programs, the Console.WriteLine
may be one of the biggest slowdowns. Here we time 100 lines written to the console.
Console.WriteLine
100 times. Each line has a single char
(not including a newline).StringBuilder.AppendLine
to merge 100 lines into a single string
, and then calls Console.WriteLine
once.Console.WriteLine
once. Combining strings before writing them is faster.int
from 0 to 1 (and back again).using System; using System.Diagnostics; using System.Text; class Program { static void Main() { int version = 1; var t1 = Stopwatch.StartNew(); if (version == 1) { // Version 1: write 100 separate lines. for (int i = 0; i < 100; i++) { Console.WriteLine("x"); } } else if (version == 2) { // Version 2: 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); } }TIME FOR VERSION 1: 35 ms TIME FOR VERSION 2: 3 ms
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.