Reputation: 11644
A non static class can have static as well as default constructor at the same time.
What is the difference between these two constructors? When shall I go for only static or static with default constructor?
Upvotes: 5
Views: 7478
Reputation: 11763
Crashing the party after everybody has left ...
Both answers are correct, just wanted to add this link : Static Constructors (C# Programming Guide).
Quoting them:
A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.
Their properties:
You can head to the above link for demo and sample code.
Upvotes: 2
Reputation: 30883
Static constructor runs once per AppDomain just before you access the instance of class first time. You can use it to initialize static variables.
On the other hand default constructor runs every time you create new instance of the class. in default constructor you can initialize non-static fields of the instance.
Upvotes: 12
Reputation: 456527
A static constructor runs only once, no matter how many objects of that type are created. A default constructor will run for each instance created by that constructor.
Upvotes: 4