C# Console Hello World


This entry is part 5 of 10 in the series C# Getting Started

The best place to start learning C# is at the beginning using a very simple example. Here we will be using Visual Studio Community 2017 to create our first C# program.

This program displays “Hello World” to the console when it is compiled and executed. That’s it. To run the code you can press F5 which will also run the debugger. Alternatively you can press Ctrl+F5 which will run the code without the debugger.

using System tells the compiler that this program uses types from the System namespace. namespace ConsoleHelloWorld declares a new namespace called ConsoleHelloWorld. This namespace starts at the opening curly brace ({) and ends at the closing curly brace (}). Curly braces define a code block. Any types declared within this block are members of the declared namespace. class Program declares a new class type called Program. Any members declared between the matching curly braces are members of this class. static void Main(string[] args) declares a method called Main as a member of the class Program. Main is the only member of class Program. main is a special function used by the compiler to define the entry point (starting point) of the program. Console.WriteLine(“Hello World!”); is a simple statement. It is part of the body of Main. This statement uses a class called Console, in the namespace System, to display a message to a window on the screen. Without the using statement at the top, the compiler wouldn’t have known where to look for the class Console.

Here below is the code you get when you create a new console application.

using System;
namespace ConsoleHelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            // The code provided will print ‘Hello World’ to the console.
            // Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app.
            Console.WriteLine("Hello World!");
            Console.ReadKey();

            // Go to http://aka.ms/dotnet-get-started-console to continue learning how to build a console app! 
        }
    }
}

When you create a new project in Visual Studio Community 2017 by going to the File menu > New > Project… you will see something similar to the screenshot below.

Main

Every C# program must have one class with a method called Main. In the program shown above, it was declared in a class called Program. The starting point of execution of every C# program is at the first instruction in Main. The name Main must be capitalized. The most simple for of Main is shown below:

        static void Main()
        {
            // statements...
        }
Series Navigation<< C# .NET CoreC# Identifiers >>