Tuesday, May 24, 2011

Static Constructors in .Net

Suppose you’re creating a class in .Net and you want certain operations only done once, at the very first time your class is used.  First thoughts?  A flag to test to see if it’s the first time into the class – suppose your class has 100 static and non-static functions – that code to do the check must be in each of those.  What a pain…  Next idea? (And, no, you’re not allowed to cheat and use a Singleton)  What?  No more ideas…

The solution – use a static constructor.  Static constructors are called only once, when the class is first used, either through static members or object members (i.e. non-statics).

Static constructors are really not much different from regular constructors in definition except they can’t have access modifiers (i.e. public, private, protected, etc).  They are called before the normal constructor.  But, being static, they can only access static members of that class.  Here’re the other rules about static constructors from Microsoft (http://msdn.microsoft.com/en-us/library/k9x6w0hc(v=VS.100).aspx):

  • A static constructor does not take access modifiers or have parameters.

  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

  • A static constructor cannot be called directly.

  • The user has no control on when the static constructor is executed in the program.

  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

  • If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

Here’s a quick example class that creates a Singleton using the static constructor.

  1: public class StaticSingleton
  2:     {
  3:         static StaticSingleton staticSingleton;
  4: 
  5:         private StaticSingleton ()
  6:         {
  7:         }
  8: 
  9:         static StaticSingleton()
 10:         {
 11:             staticSingleton = new StaticSingleton();
 12:         }
 13: 
 14:         public static StaticSingleton GetInstance()
 15:         {
 16:             return staticSingleton;
 17:         }
 18:     }

Here’s the non-static constructor version for comparison:

  1:     public class Singleton
  2:     {
  3:         static Singleton singleton;
  4: 
  5:         private Singleton()
  6:         {
  7:         }
  8: 
  9:         public static Singleton GetInstance()
 10:         {
 11:             if (singleton == null)
 12:             {
 13:                 singleton = new Singleton();
 14:             }
 15:             return singleton;
 16:         }
 17:     }

No comments:

Post a Comment