Why isn't the static constructor from my base class called?

Avi Turner picture Avi Turner · Nov 20, 2013 · Viewed 8.1k times · Source

Lets say I have 2 classes:

public abstract class Foo
{
    static Foo()
    {
        print("4");
    }
}

public class Bar : Foo
{
    static Bar()
    {
        print("2");
    }

    static void DoSomething()
    {
        /*...*/
    }
}

I expected that after calling Bar.DoSomething() (assuming this is the first time I access the Bar class) the order of event will be:

  1. Foo's static constructor (again, assuming first access) > print 4
  2. Bar's static constructor > print 2
  3. Execution of DoSomething

At the bottom line I expect 42 to be printed.
After testing, it seems that only 2 is being printed.
And that is not even an answer.

Can you explain this behavior?

Answer

dav_i picture dav_i · Nov 20, 2013

The specification states:

The static constructor for a class executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

  1. An instance of the class is created.
  2. Any of the static members of the class are referenced.

Because you are not referencing any of the members of the base class, the constructor is not being excecuted.

Try this:

public abstract class Foo
{
    static Foo()
    {
        Console.Write("4");
    }

    protected internal static void Baz()
    {
        // I don't do anything but am called in inherited classes' 
        // constructors to call the Foo constructor
    }
}

public class Bar : Foo
{
    static Bar()
    {
        Foo.Baz();
        Console.Write("2");
    }

    public static void DoSomething()
    {
        /*...*/
    }
}

For more information: