The Console Class

The Console class has been used since the beginning of Chapter 1, so now would be a good time to examine it in more detail.

The System.Console class provides access to the standard input, standard output, and standard error streams. Standard input represents the stream from which input normally arrives; for a console application, this is the keyboard. Standard output represents the stream where output is normally sent, and for a console application, this is the console window. Standard error is a stream to which error messages can be written, and this defaults to the console window. Two separate output streams are provided because it is possible to redirect standard output to a file or another device, and you will probably want to see your error messages displayed on the screen rather than being sent along with your other output.

In this section, only console I/O is considered. The topic of I/O in general is covered more fully in Chapter 6.

One thing that sometimes puzzles people new to .NET is that it is possible to use the Console class in two ways, as shown in the following code:

Console.Writeline ("this is the first way")

Console.Out.Writeline ("this is the second way")

Out is a TextWriter, a shared member of the Console class, which writes to standard output, and the Writeline method belongs to Out. The Console class provides a shortcut by implementing Writeline as a shared method that delegates to the Out object, and thus saves you four characters every time you use an output statement. A similar shortcut is provided for Console.In, but if you want to write to standard error, you have to use the full form.

In comparison with some languages (such as Java), console I/O is very simple and there are few methods to master. The Writeline() and Write() methods output text with and without a trailing new line respectively; Read() gets the next character from the input stream, and Readline() obtains a complete line of text. Although it hasn't yet been used in this book, it is possible to produce formatted output; this topic is covered in the Immediate Solutions section at the end of this chapter.

0 0

Post a comment