Static Keyword in C#

 

A C# class can contain both static and non-static members. When we declare a member with the help of the keyword static, it becomes a static member. A static member belongs to the class rather than to the objects of the class. Hence static members are also known as class members and non-static members are known as instance members.

In C#, data fields, member functions, properties and events can be declared either as static or non-static. Remember that indexers in C# can’t declared as static. Static fields can be declared as follows by using the keyword static.

class MyClass

{

    public static int x;

    public static int y = 20;

}

 

When we declare a static field inside a class, it can be initialized with a value as shown above. All un-initialized static fields automatically get initialized to their default values when the class is loaded first time.

 

using System;

class MyClass

{

        public static int x = 20;

        public static int y;

         public static int z = 25;

         public MyClass(int i)

        {

              x = i;

              y = i;

              z = i;

         }

     }

 

 

class MyClient

{

         public static void Main()

         {

               Console.WriteLine("{0},{1},{2}",MyClass.x,MyClass.y,MyClass.z);

              MyClass mc = new MyClass(25);

 

              Console.WriteLine("{0},{1},{2}",MyClass.x,MyClass.y,MyClass.z);

          }

}

 

The C# provides a special type of constructor known as static constructor to initialize the static data members when the class is loaded at first. Remember that, just like any other static member functions, static constructors can’t access non-static data members directly.

The name of a static constructor must be the name of the class and even they don’t have any return type. The keyword static is used to differentiate the static constructor from the normal constructors. The static constructor can’t take any arguments. That means there is only one form of static constructor, without any arguments. In other way it is not possible to overload a static constructor.

We can’t use any access modifiers along with a static constructor.

using System;

class MyClass

{

         public static int x;

         public static int y;

         static MyClass ()

         {

               x = 100;

               Y = 200;

         }

}

class MyClient

{

          public static void Main()

         {

                  Console.WriteLine(“{0},{1},{2}”,MyClass.x,MyClass.y);

         }

}

 

Note that static constructor is called when the class is loaded at the first time. However we can’t predict the exact time and order of static constructor execution. They are called before an instance of the class is created, before a static member is called and before the static constructor of the derived class is called.