What's the best way to ensure a base class's static constructor is called?

13,129

Solution 1

The rules here are very complex, and between CLR 2.0 and CLR 4.0 they actually changed in subtle and interesting ways, that IMO make most "clever" approaches brittle between CLR versions. An Initialize() method also might not do the job in CLR 4.0 if it doesn't touch the fields.

I would look for an alternative design, or perhaps use regular lazy initialization in your type (i.e. check a bit or a reference (against null) to see if it has been done).

Solution 2

You may call static constructor explicity, so you will not have to create any methods for initialization:

System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof (TypeBase).TypeHandle);

You may call it in static constructor of derived class.

Solution 3

As others have noted, your analysis is correct. The spec is implemented quite literally here; since no member of the base class has been invoked and no instance has been created, the static constructor of the base class is not called. I can see how that might be surprising, but it is a strict and correct implementation of the spec.

I don't have any advice for you other than "if it hurts when you do that, don't do that." I just wanted to point out that the opposite case can also bite you:

class Program 
{
  static void Main(string[] args)
  {      
    D.M();
  }      

}
class B 
{ 
  static B() { Console.WriteLine("B"); }
  public static void M() {}
} 
class D: B 
{ 
  static D() { Console.WriteLine("D"); }
}

This prints "B" despite the fact that "a member of D" has been invoked. M is a member of D solely by inheritance; the CLR has no way of distinguishing whether B.M was invoked "through D" or "through B".

Solution 4

In all of my testing, I was only able to get a call to a dummy member on the base to cause the base to call its static constructor as illustrated:

class Base
{
    static Base()
    {
        Console.WriteLine("Base static constructor called.");
    }

    internal static void Initialize() { }
}

class Derived : Base
{
    static Derived()
    {
        Initialize(); //Removing this will cause the Base static constructor not to be executed.
        Console.WriteLine("Derived static constructor called.");
    }

    public static void DoStaticStuff()
    {
        Console.WriteLine("Doing static stuff.");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Derived.DoStaticStuff();
    }
}

The other option was including a static read-only member in the derived typed that did the following:

private static readonly Base myBase = new Base();

This however feels like a hack (although so does the dummy member) just to get the base static constructor to be called.

Solution 5

I almost alway regret relying on something like this. Static methods and classes can limit you later on. If you wanted to code some special behavior for your Type class later you would be boxed in.

So here is a slight variation on your approach. It is a bit more code but it will allow you to have a custom Type defined later that lets you do custom things.

    abstract class TypeBase
    {
        private static bool _initialized;

        protected static void Initialize()
        {
            if (!_initialized)
            {
                Type<int>.Instance = new Type<int> {Name = "int"};
                Type<long>.Instance = new Type<long> {Name = "long"};
                Type<double>.Instance = new Type<double> {Name = "double"};
                _initialized = true;
            }
        }
    }

    class Type<T> : TypeBase
    {
        private static Type<T> _instance;

        public static Type<T> Instance
        {
            get
            {
                Initialize();
                return _instance;
            }
            internal set { _instance = value; }
        }

        public string Name { get; internal set; }
    }

Then later when you get to adding a virtual method to Type and want a special implementation for Type you can implement thus:

class TypeInt : Type<int>
{
    public override string Foo()
    {
        return "Int Fooooo";
    }
}

And then hook it up by changing

protected static void Initialize()
{
      if (!_initialized)
      {
          Type<int>.Instance = new TypeInt {Name = "int"};
          Type<long>.Instance = new Type<long> {Name = "long"};
          Type<double>.Instance = new Type<double> {Name = "double"};
          _initialized = true;
       }
}

My advice would be to avoid static constructors - it is easy to do. Also avoid static classes and where possible static members. I am not saying never, just sparingly. Prefer a singleton of a class to a static.

Share:
13,129
Dan Tao
Author by

Dan Tao

Author of the blog The Philosopher Developer and the open source libraries lazy.js and nearest-color (among others), and cohost of the podcast Spaceflix. GitHub: dtao Twitter: @dan_tao SoundCloud: dantao I’m the Head of Engineering for Bitbucket Cloud. Previously I've worked at Google, Cardpool, and ThoughtWorks.

Updated on June 04, 2022

Comments

  • Dan Tao
    Dan Tao about 2 years

    The documentation on static constructors in C# says:

    A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.

    That last part (about when it is automatically called) threw me for a loop; until reading that part I thought that by simply accessing a class in any way, I could be sure that its base class's static constructor had been called. Testing and examining the documentation have revealed that this is not the case; it seems that the static constructor for a base class is not guaranteed to run until a member of that base class specifically is accessed.

    Now, I guess in most cases when you're dealing with a derived class, you would construct an instance and this would constitute an instance of the base class being created, thus the static constructor would be called. But if I'm only dealing with static members of the derived class, what then?

    To make this a bit more concrete, I thought that the code below would work:

    abstract class TypeBase
    {
        static TypeBase()
        {
            Type<int>.Name = "int";
            Type<long>.Name = "long";
            Type<double>.Name = "double";
        }
    }
    
    class Type<T> : TypeBase
    {
        public static string Name { get; internal set; }
    }
    
    class Program
    {
        Console.WriteLine(Type<int>.Name);
    }
    

    I assumed that accessing the Type<T> class would automatically invoke the static constructor for TypeBase; but this appears not to be the case. Type<int>.Name is null, and the code above outputs the empty string.

    Aside from creating some dummy member (like a static Initialize() method that does nothing), is there a better way to ensure that a base type's static constructor will be called before any of its derived types is used?

    If not, then... dummy member it is!

  • Dan Tao
    Dan Tao over 13 years
    Yes, yes it does... but maybe that's the only way?
  • Joshua Rodgers
    Joshua Rodgers over 13 years
    I was able to get a call to a dummy Initialize() member that didn't touch the fields to with with CLR 4.0. As per the code I posted in my answer.
  • Joshua Rodgers
    Joshua Rodgers over 13 years
    Yeah, it seems like the only way. Beyond your solution and the dummy static field that creates a base, I can't find any other ways of doing this.
  • LukeH
    LukeH over 13 years
    @Joshua: So long as the base class has a static constructor -- not just field initialisers -- then calling Initialize is guaranteed to call that constructor because the type won't be marked beforefieldinit. As the spec says, the static constructor will be called "...before the first instance is created or any static members are referenced". And since the question is asking about how to force the static constructor to fire then we can assume that there'll be one.
  • LukeH
    LukeH over 13 years
    Having said that, relying on obscure corners of the spec to guarantee functionality isn't a great idea, especially when someone unfamiliar with that corner of the spec comes along to update the code a few years down the line. Much better to do something explicit and obviously correct, as you suggest.
  • Dan Tao
    Dan Tao over 13 years
    I had been trying to implement the idea I suggested in this answer based on SLaks's suggestion of using a generic static type instead of a dictionary. My thinking was that deriving from a non-generic type and using that base type's static constructor to initialize the "dictionary" would be an elegant solution; now that I realize it would require a hack to utilize such a constructor (e.g., a dummy member), I see that you're right (cont.)...
  • Dan Tao
    Dan Tao over 13 years
    ...and a different design altogether would make more sense. What I'm thinking I'll do is just ditch the "base type" idea completely and simply use a separate internal class to perform the initialization I want.
  • Merlyn Morgan-Graham
    Merlyn Morgan-Graham over 13 years
    +1: While this doesn't address the specific problem, I think it is good advice.
  • Merlyn Morgan-Graham
    Merlyn Morgan-Graham over 13 years
    +1 This seems to work. As with any static initialization order solution, I'm dubious as to whether it is bulletproof, but at least it doesn't seems to run the static ctor twice if you invoke this twice, in a simple single-threaded app.
  • TrueWill
    TrueWill over 13 years
    ...and prefer IoC Containers to Singletons. :)
  • devios1
    devios1 over 13 years
    Any idea of the performance of this method? Does it use reflection and/or is it fast if the static constructor has already been called?
  • Tod Thomson
    Tod Thomson over 10 years
    This is the way to do it - to replicate base() in static constructors just call RuntimeHelpers. RunClassConstructor(typeof(TypeBase).TypeHandle); at the beginning of each constructor.
  • Erik Philips
    Erik Philips over 7 years
    Second link is dead :(
  • T McKeown
    T McKeown over 4 years
    it's good idea, but implementation isn't thread safe (and it really should be, for something like this)