views:

104

answers:

4

What are the differences between the two? I've only used one kind of constructor and I believe it's the static constructor. Only familiar with C++ and Java.

+4  A: 

Static constructor is called the first time your class is referenced i.e.

MyClass.SomeStaticMethod()

Instance constructor is called every time you do 'MyClass dummy = new MyClass()' i.e. create instance of the class

Semantically first is used when you want to ensure that some static state is initialized before it is accessed, the other is used to initialize instance members.

Hasan Khan
A: 

The static constructor runs only once for all instances or uses of the class. It will run the first time you use the class. Normal constructors run when you instantiate an object of the class.

Everything you should need to know about static constructors can be found here: http://msdn.microsoft.com/en-us/library/k9x6w0hc(v=VS.100).aspx

Steven Oxley
+3  A: 

Static constructors allow you to initialize static variables in a class, or do other things needed to do in a class after it's first referenced in your code. They are called only once each time your program runs.

Static constructors are declared with this syntax, and can't be overloaded or have any parameters because they run when your class is referenced by its name:

static MyClass()
{
}

Instance constructors are the ones that are called whenever you create new objects (instances of classes). They're also the ones you normally use in Java and most other object-oriented languages.

You use these to give your new objects their initial state. These can be overloaded, and can take parameters:

public MyClass(int someNumber) : this(someNumber, 0) {}

public MyClass(int someNumber, int someOtherNumber)
{
    this.someNumber = someNumber;
    this.someOtherNumber = someOtherNumber;
}

Calling code:

MyClass myObject = new MyClass(100, 5);
BoltClock
A: 

static constructor is initialized only at first time call

it will never be initialize again

PokemonCraft