views:

168

answers:

4

I am reading a code in C# that uses two constructors. One is static and the other is public. What is the difference between these two constructors? And for what we have to use static constructors?

+13  A: 

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.

Konrad Rudolph
+2  A: 

Static Constructor... It is guaranteed to be called "once" througout the life of the application/app Domain. It can contain statements that you want to be executed only once.

Public Constructor... Since we can not add access modifiers to a static constructor, a public constructor means you are talking about an instance constructor. If an instance constructor is public then the outside world can create its instances. Other options are Internal ( can be called from within the library), Private ( from within the class only).

Amby
Is a static constructor guaranteed to be called once? What if the type is never used within the lifecycle of an app?
MPritch
@MPritch, you are right in that case it won't be called. But i don;t even need to worry about the things that a class is doing (or not doing) if i am not using (or referring) it anywhere in my application, rite?
Amby
@Amby: that all depends on what you're doing in the constructor
MPritch
+4  A: 

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.
}
Ondrej Slinták
A: 

Check this if helps.

Ram