Thursday, July 28, 2011

Private and Static Constructors in C#

Private and Static constructors are rarely used. Mostly we tend to create only public conctructors when we create a class.

Private Constructors are used to prevent creating  instances of a class. If a class has only static members or methods, the declaration of the empty constructor doesn't let the automatic generation of a default constructor.

If you try to instantiate a class, when you build your application you've got the error "... is inaccessible due to its protection level".

Private constructor is used  in Singleton design pattern. You can be sure external code never creates a singleton instance accidentally. Private constructor prevents access to the object constructor.

Example code :
public class Person
{
    private Person()
    {
    }
    public static void Speak()
    {
        Console.WriteLine("I spoke");
    }  
}

class Program
{
    static void Main(string[] args)
    {
        Person person = new Person();
        // Test.StaticConstructor.Person.Person()' is inaccessible 
due to its protection level
        Console.Read();
    }
}

Static constructors are use to initialize any static data when any static method is invoked or static member is referenced or when you create an instance of a class which has static constructor.

This static constructor called only once. Beside that static constructor doesn't take any access modifiers or have any parameters.

Most common usage of it is to write logs into a file when class is used. In addition, it's used to set default value  to static members in class.

You can be sure that static constructor is thread safe.

In static constructor you can not access any members or methods which are not static.

Remember, if any exception is thrown inside static constructor the runtime can not call a second time and it remains uninitialized for the life time of application.

Example code :
public class Car
{
    static Car() 
    {
        Console.WriteLine("Static constructor is called");
    }

    public static string Color;
    public static void Drive() 
    {
        Console.WriteLine("Car is driven");
    }
}
class Program
{
    static void Main(string[] args)
    {
        Car.Drive(); // static constructor is invoked
        Car car = new Car(); // static constructor is not invoked
        Car.Color = "Green"; // static constructor is not invoked

        Console.Read();
    }
}

Output :
Static constructor is called
Car is driven

0 comments: