Ram
Ram

Reputation: 11644

Static and default constructor

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

Answers (3)

Noctis
Noctis

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:

  • A static constructor does not take access modifiers or have parameters.
  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  • A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
  • If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

You can head to the above link for demo and sample code.

Upvotes: 2

Giorgi
Giorgi

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

Stephen Cleary
Stephen Cleary

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

Related Questions