简体   繁体   中英

Static Constructor in derived class getting invoked first then the base class

I am wondering, generally in C#, the constructor concept is, base class cons should execute first, but why is that I am seeing derived class static constructor getting called and then base class cons. Could someone please explain ? :(

Static constructors initialize the class itself , which is to say that they must be called before any other static members are accessed, and before the creation of any instances of the class.

As for the ordering of calls to static constructors within a class hierarchy, you should consider that undefined. From the MSDN page on static constructors :

The user has no control on when the static constructor is executed in the program.

Well, that's the whole point of static constructors; it has nothing to do with inheritance.

To quote MSDN

A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

You can declare their body, but don't need to worry about when they will be called (nor does the framework give you any guarantee in that regard, except that it will run before any instance of the class at hand has been created).

Edit

Oh, there is something else you should be aware of, and it has to do with generics, even though it might be obvious.

Consider this snippet:

class Foo<T> {
    static Foo() {
        Console.WriteLine("Danger, Will Robinson!");
    }
}

Here the static constructor will be executed for whatever T , because of course:

typeof(Foo<Bar>) != typeof(Foo<Baz>)

Static constructor of Derived class is called first because it is loaded before Base class. Constructor is called when the class is loaded into the memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM