Static Constructors

A static constructor is invoked automatically before the first instance of the class is created or any static members are referenced. It initializes static data members when the class is referenced first time.

Why is a static constructor used?
  • A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only.
  • Typical use of static constructors – When the class is using a log file, the static constructor can be used to write entries to the log file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

Properties of static constructors
  • A static constructor does not take access modifiers or have parameters.
  • The execution of a static constructor is triggered automatically when the first instance of the class is created or any static members are referenced.
  • A static constructor cannot be called directly.
  • The user has no control on the execution of static constructor.

Example: In this example, the class Bus has a static constructor and one static member, Drive(). When Drive() is called, the static constructor is invoked to initialize the class.

public class Bus
{
    // Static constructor:
    static Bus()
    {
        System.Console.WriteLine("The static constructor invoked.");
    }

    public static void Drive()
    {
        System.Console.WriteLine("The Drive method invoked.");
    }
}

class TestBus
{
    static void Main()
    {
        Bus.Drive();
    }
}

Output:  
The static constructor invoked.
The Drive method invoked.

No comments:

Post a Comment