Thursday, 25 August 2011

Static Constructors

    A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.

Static constructors have the following properties:
  • A static constructor does not take access modifiers or have parameters.
  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  • A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

    The following Program describes about the static constructor...



class sample
    {
         public static int i;
         public int j;
         static sample()
        {
            i = 10;
            //j = 11; Error:: An object reference is required for the non-static field, method, or property .

            Console.WriteLine("static constructor is invoked");
        }

        public sample()
        {
            int j = 22;
            Console.WriteLine("Non Static Constructor is invoked");
        }
           
    }

                                                     

    class Program
    {
      
        static void Main(string[] args)

        {
            Console.WriteLine("i value is " + sample.i);
         // Static constructor is called before object creation.
            sample obj = new sample();
            Console.WriteLine("J value is " + obj.j);
            Console .Read();

        }
    }

Output:
static constructor is invoked
i value is 10
Non Static Constructor is invoked
J value is 0





No comments:

Post a Comment