Program Structure

Introduction

In previous post we have seen how to create a console application, in fact we have written small “Hello” program. So before moving further let’s understand minimum C# program structure.

For reference will take same “Hello” example from previous post.

 Here is source code:

using System;

namespace MyFirstApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello");
            Console.ReadLine();
        }
    }
}

If we see above example, we can divide the above program into 4 parts

  • using directive
  • Namespaces
  • Class
  • Main method

using directive

The using directive loads a specific namespace from a referenced assembly. It is usually placed in the top (or header) of a code file but it can be placed elsewhere if wanted, e.g. in the above example, we need system assembly because we are using Console.WriteLine or Console.ReadLine and respective classes are defined inside of System assembly. In order to run this program, we need to add a system directive.

using System;

namespace

Namespaces allow to group entities like classes, objects and functions under a name.

So, we have group class under A namespace MyFirstApplication

namespace MyFirstApplication

Class

A class is a blueprint from which objects are made. For now, don’t think much on this will talk later on the same. Just understand that since C# is an Object-Oriented Programming (OOP) language, any and every instruction, you write for the computer to understand, should be written inside a class.

In above example we have defined our class

class Program

Main method

Every program must have an entry point from where the program should start. The entry point of the C# application is the Main method. There can only be one, and it is a static method in a class. The method usually returns void and is passed command-line arguments as an array of strings.

In above example we have defined the below entry point

static void Main(string[] args)

So, to sum up, a computer language is a mix of syntax and keywords which aid you to give instructions to the computer to perform a certain task. In C#, to run the program we have a minimum requirement to define the program structure


Leave a Reply

Your email address will not be published. Required fields are marked *