0

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.

1 Answer 1

2

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 
Sign up to request clarification or add additional context in comments.

1 Comment

I'm unable to find the right passage in the C# specification. I'm pretty sure it's in there, I just can't seem to find the right phrase to search for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.