This is a mirror of official site: http://jasper-net.blogspot.com/

Static constructor in C#

| Monday, May 31, 2010
Did you ever implement a singleton in c#? For those who don't know what a singleton is, it is a class which can only have one instance, more on Wikipedia. The preferred implementation of a singleton in c# is the following.

public sealed class Singleton
{
  //single instance
  private static readonly Singleton instance = new Singleton();
 
  //private constructor
  private Singleton(){}

  public static Singleton Instance
  {
     get
     {
        return instance;
     }
  }
}

But what would you do if you want to execute some custom code before the instance of the singleton is initialized? You can use the classic singleton code which isn't really different than in other programming languages.

Read more: Baldi's Blog

Posted via email from jasper22's posterous

0 comments: