Social Developer
Social Developer

Reputation: 425

Derived.<static variable from Base> doesn't invoke derived's static constructor

Why isn't the static constructor in Derived invoked in the following code?

class Base
{
    public static Base Instance;
    static Base() { Console.WriteLine("Static Base invoked."); }
}

class Derived : Base
{
    static Derived() { 
        Instance = new Derived();
        Console.WriteLine("Static Derived invoked."); 
    }
}

void Main()
{
    var instance = Derived.Instance;
}

OUTPUT:
Static Base invoked.

Upvotes: 0

Views: 32

Answers (1)

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391456

This is because accessing a static member of a base class through a derived class is in fact compiled to go through the base class, the one that declared that member.

As such, this:

Derived.Instance

is actually compiled like this:

Base.Instance

Thus no code is touching Derived, and that's why its static constructor is not called.

Here's how your Main method is compiled (release):

IL_0000:  ldsfld      Base.Instance
IL_0005:  pop
IL_0006:  ret 

Upvotes: 2

Related Questions