Hello World - A First Command Line Program


Below is the first command line project.

// HelloWorld - A First Command Line Project

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Hello World");
    }
}

To get started with this first program, a little about namespaces, classes and functions needs to be known. These are advanced topics. Briefly, namespaces contain classes. The System namespace contains the class Console. The class Console contains a static function called WriteLine. This function is used to write a string to the system console.

The program begins with a comment. The first identifier in the comment is the name of the project, followed by a brief description of what the program is intended to demonstrate.

Next, the namespace System is brought into view via the statement

using System;

This makes the types declared in the System namespace visible to the program at hand. These types include the Console data type which is used further down in the program.

Classes and functions (methods) are covered later in the volume. However, to get a program running, classes and functions must be used. Thus a small amount of elucidation on classes and functions is required to get started.

In C#, methods must be contained within a class (there are no global functions like in C++). This explains why the function Main (the function at which the program commences) must be contained in a class. In the above program, the containing class is simply called Program. All of the console based programs in this volume follow this pattern. The name "Program" (for the class) is entirely arbitrary and could be chosen to be other names. Thus, the pattern for a command line program in C# is as follows.

class ClassName
{
    static void Main()
    {
     ...
    }
}

The function Main is a special function and it must be declared as static. It is the entry point to the program. There are a number of forms that the declaration of Main can take. In its simplest form (as above), the function takes no parameters and returns no value (hence has void return type).

Inside Main() a string is printed to the console. The line is shown again below.

Console.WriteLine("Hello World");

"Hello world" is a string literal. Strings are covered in more detail later.

To compile and execute this example, enter the Visual Studio workbench and select the project \CSharp\Projects\HelloWorld. By convention, each of the samples have the project name at the beginning of the comment at the top of the program. Build the project. Then run the project using Ctrl+F5. Make sure the function lock is turned on. What appears is:

Hello World

This completes the first C# program covered by this book. For a beginner, it is a steep learning curve because namespaces, classes and methods are all required. Once this first program is understood, the rest of the programs of this volume follow a similar pattern.