Search code examples
c#inheritancestatic-constructorobject-initialization

Initialize instance of singleton descendant


In a traditional singleton, you can initialize the instance like so:

private static readonly Messages _instance = new Messages();

Then you access it via a getter, like so:

    public static Messages Instance {
        get {
            return _instance;
        }
    }

In this case, we have a parent and multiple descendants.

In the parent we have

    protected static Base _instance;
    public static Base Instance {
        get {
            return _instance;
        }
    }

In the descendant, we use the class constructor to populate the static variable.

    static Derived() {
        _instance = new Derived();
    }

This should work because the class constructor is called when the class is first referenced, before it is used. For some reason, this is not working.

   Derived.Instance.Initialize();

fails because Instance is null and the breakpoint in the constructor is never hit.

Update: The Base constructor gets called, but the Derived constructor does not. This may be because the static constructor is triggered when a static method is called on the class. The static method I am calling is on the parent, not the descendant.


Solution

  • The static method I am calling is on the parent, not the descendant.

    This was the problem. The class constructor of the base was called because a static method belonging to the parent was called.

    The descendant class constructor isn't called until a static method is called on the descendant.

    Derived1.EmptyStaticMethod(); //This provokes the class constructor
    Derived2.EmptyStaticMethod();
    Derived1.Instance.Initialize(); // This now works.