Static and standard constructor

A non-stationary class can have both a static and a standard constructor at the same time.

What is the difference between these two constructors? When should I go only static or static with the default constructor?

+4
source share
3 answers

The static constructor runs once in the AppDomain just before you first access the class instance. You can use it to initialize static variables.

On the other hand, the default constructor starts every time a new instance of the class is created. in the default constructor, you can initialize non-static instance fields.

+9
source

A static constructor runs only once, regardless of how many objects of this type are created. The default constructor will be launched for each instance created by this constructor.

+3
source

The party crashes after everyone is gone ...

Both answers are correct, just add this link: Static constructors (C # Programming Guide) .

Quoting them:

The static constructor is used to initialize any static data or to perform a specific action that needs to be performed only once. It is called automatically before the creation of the first instance or reference to any static members.

Their properties:

  • The static constructor does not accept access modifiers or has no parameters.
  • The static constructor is called automatically to initialize the class before creating the first instance or referencing any static members.
  • A static constructor cannot be called directly.
  • The user cannot control when the static constructor is executed in the program.
  • A typical use of static constructors is when a class uses a log file and a constructor is used to write records to this file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
  • If the static constructor throws an exception, the runtime will not throw 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 go to the link above for a demo and sample code.

0
source

Source: https://habr.com/ru/post/1309986/


All Articles