开发者

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 开发者_JS百科shall I go for only static or static with default constructor?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜