Share via


Static Keyword and Main Method functionalities in c#.net

Introduction

In order to memory management some keywords are playing vital role in development programming languages. In this article you will learn depth information about static keyword. 

You cannot find definition for static,abstract,sealed and more keywords. Those definitions strictly ruled into compilers. So a rule has been framed into compiler to enclosed main with static keyword. Here i want to say difference between  c# compiler and other programming compiler(java). 

class Program
    {
public static void Display()
        {
            Console.WriteLine("Static Method");
        }
     }

Static void main()
{
 Program objprogram = new Program();
 objprogram.Display();
}

'Program.Display()' cannot be accessed with an instance reference; qualify it with a type name instead

it comes when you trying to call static methods from object reference. But it error won't come in java if program object reference trying to call static methods.

**Why c# framed such rule for static ?
**
C# made some special features on compiler to predict some errors and issues. In other programming we will find lot of errors after compilation and wont produce proper results at run time, Compiler gives error free screen but won't produce output.  To makes better interpreter works for C# framed rules to produce errors and violations. So these rules helped us to follow better principles to programming.

Interpreter finds main function and start execution from it. Before compiler check rules, if main enclosed static keyword or not.

Why Main function should enclosed Static Keyword ? 

If main not enclosed with static keyword, you have a chance to  initialize from some where in your program.