Console Applications

The simplest type of application is a console application. This application doesn't have much of a user interface; in fact, for those old enough to remember the MS-DOS operating system, a console application looks just like an MS-DOS application. It works in a command window without support for graphics or input devices such as a mouse. A console application is a text-based user interface that displays text characters and reads input from the keyboard.

The easiest way to create a console application is to use Visual Studio. For the current discussion let's just look at a sample source file for a Console application, as shown in the following example. Notice that the console application contains a single method, a Sub called Main. By default if you create a console application in Visual Studio, the code located in the Sub Main is the code which is by default started. However, the Sub Main isn't contained in a class, instead the Sub Main that follows is contained in a Module:

Module Module1 Sub Main()

Console.WriteLine("Hello World")

Dim line = Console.ReadLine() End Sub End Module

A Module isn't truly a class, but rather a block of code that can contain methods, which are then referenced by code in classes or other modules — or, as in this case, it can represent the execution start for a program. A Module is similar to having a Shared class. The Shared keyword indicates that only a single instance of a given item exists.

For example in C# the Static keyword is used for this purpose, and can be used to indicate that only a single instance of a given class exists. Visual Basic doesn't support the use of the Shared keyword with a Class declaration; instead Visual Basic developers create modules that provide the same capability. The Module represents a valid construct to group methods that don't have state-related or instance-specific data.

Note a console application focuses on the Console Class. The Console Class encapsulates Visual Basic's interface with the text-based window that hosts a command prompt from which a command-line program is run. The console window is best thought of as a window encapsulating the older non-graphical style user interface, whereby literally everything was driven from the command prompt. A Shared instance of the Console class is automatically created when you start your application, and it supports a variety of Read and Write methods. In the preceding example, if you were to run the code from within Visual Studio's debugger, then the console window would open and close immediately. To prevent that, you include a final line in the Main Sub, which executes a Read statement so that the program continues to run while waiting for user input.

Was this article helpful?

0 0

Post a comment