Tuesday, August 9, 2016

Public and static constructor

public constructor - users of the class can call that constructor (opposite is private).

static constructor  -  not belongs to an instance of a class but to the class itself. it is called once, automatically (.NET runtime itself ), when the class is used for the first time. No need public or private since cannot called manually.

If you have Public and static constructor together, static constructor will run 1st. When refresh it , static constructor would not run.

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