Static Constructor… saved my day

Alsalam alikom wa ra7mat Allah wa barakatoh (Peace upon you)

I was designing some classes today and I got stuck with an old problem I used to fix in an ugly way…

 class A
{
    public static void InitializeMe()
    {
        SomeClassManager.Listeners.Add(typeof(A));
    }
}

It would have been easy if:

  • You know when exactly to call InitializeMe() so that you get hooked up at the right time (before Listeners start iterating over its elements)
  • You know what classes contain an InitializeMe function.. you can use reflection to get a list of all classes and then check whether they have the method or not.. –you can’t use interfaces as they don’t allow static members-

What if you are designing a plugin model for an application, and want to call some static initialization code… again you will have to do reflection (which is slow).

And here comes static constructors!

 class A
{
    static A()
    {
        InitializeMe();
    }

    public static void InitializeMe()
    {
        SomeClassManager.Listeners.Add(typeof(A));
    }
}

That simple.. Static Constructor [MSDN Link] will be called once this type is “loaded” which happens in .NET when your assembly first gets loaded into memory.. which is exactly the time I wanted… and it saved my day!

P.S, Check MEF (Managed Extensibility Framework) if you are interested in supporting plugins in ur apps, https://www.codeplex.com/MEF

And here is a getting started guide, https://code-inside.de/blog-in/2008/11/19/howto-first-steps-with-mef-hello-mef/

Comments