Calling of Static Constructor and Instance Constructor

前端 未结 3 1094
礼貌的吻别
礼貌的吻别 2021-02-02 03:52

As I know Constructors of parent class is called first and then child Class.But why In Case of static Constructor It executes from derived Class first and then Child Class?

3条回答
  •  借酒劲吻你
    2021-02-02 04:50

    Static Constructors are always executed before the non-static constructor. Static constructor is called when class is accessed first time.

    • Static Constructors

    From MSDN Doc,

    • 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.

提交回复
热议问题