Wednesday 13 April 2016

Chetu Interview Question

Difference between Public and Static Constructor

static and public are orthogonal concepts (i.e. they don’t have anything to do with each other).
public simply means that users of the class can call that constructor (as opposed to, say, private).
static means that the method (in this case the constructor) belongs not to an instance of a class but to the “class itself”. In particular, a static constructor is called once, automatically, when the class is used for the first time.
Furthermore, a static constructor cannot be made public or private since it cannot be called manually; it’s only called by the .NET runtime itself – so marking it as public wouldn’t be meaningful.
Static constructor runs just once, before your class is instantiated. It's used if you want something to happen just once. A nice example would be a Bus class (similar to something they explain in MSDN article):

public class Bus
{
    public static int busNo = 0;

    static Bus()
    {
        Console.WriteLine("Woey, it's a new day! Drivers are starting to work.");
    }

    public Bus()
    {
        busNo++;

        Console.WriteLine("Bus #{0} goes from the depot.", busNo);
    }
}


class Program
{
    static void Main(string[] args)
    {
        Bus busOne = new Bus();
        Bus busTwo = new Bus();
    }

    // Output:
    // Woey, it's a new day! Drivers are starting to work.
    // Bus #1 goes from the depot.
    // Bus #2 goes from the depot.

}

No comments:

Post a Comment