Saturday, July 30, 2011

What are Static Constructors and how Static Constructors are invoked?

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.
Example :-


OUTPUT of above code :


NOTE : Static Constructors doesn't take any Access Modifier. This is rule. By default is private.

    class A
    {
        /// <summary>
        /// Static Constructors doesn't take any Access Modifier. This is rule.
        /// </summary>
        static A()
        {
            Console.WriteLine("A : Static Constructor.");
        }

       /// <summary>
        /// Default Constructor
        /// </summary>
        public A()
        {
            Console.WriteLine("A : Default Constructor.");
        }
    }

When we have static constructors in our class then it would be called first.
There can be several scenarios with static constructors.

1.       If we have static and default constructors in same class then first Static constructor would be called then Default.
2.       If we have three classes A,B,C have static constructors and are inherited in such a way C:B:A, then constructors would be invoked in following sequence :-
a.       Default Constructors would be called in A:B:C sequence. Rule is, first base class default constructor will call then derived class default constructor.
b.      Static Constructors would be called in C:B:A sequence. (Opposite to invocation of Default Constructors.). Rule is, first derived class static constructor will be called then base class static constructor.

Here is the example of the same.
Making object of class C all constructors would get invoked. First all static constructors then default constructors.


Hence we can say that :-
1.       For static constructor : First derived class static constructor will be called then base class static constructor.
2.       For default constructor : First base class default constructor will call then derived class default constructor.

Another example: 




No comments:

Post a Comment