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:
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, http://www.codeplex.com/MEF And here is a getting started guide, http://code-inside.de/blog-in/2008/11/19/howto-first-steps-with-mef-hello-mef/