Ivan and the other guys in Wellington had their last Lunch with Geeks about Design Patterns. And came out with that idea:

The most overused design pattern : Singleton. With the remark that a singleton should only be used when you need to keep state in your object internally.

So, just to reinforce that concept, here is a VS2005 code snippet to quickly create a Singleton. I uploaded it on GotCodeSnippets.NET, a repository of code snippets.

Download the Singleton VS2005 code snippet.

It expands to the following code:

public sealed class Singleton
{
    private readonly static Singleton _instance = new Singleton();

    public static Singleton Current
    {
         get
        {
            return _instance;
        }
    }

    private Singleton()
    {
           //Implement here the initialization of your singleton
    }
}

You can get more information about the Singleton pattern on the DoFactory site and on Jon Skeet's article. But beware the Singleton: Why Singleton are Evil.

Technorati tags: ,
posted on Sunday, August 12, 2007 8:29 AM

Comments on this entry:

# re: Singleton with VS2005 snippet

Left by Nic Wise at 8/12/2007 12:25 AM

I usually init the instance in the get, so it's effectivly demand loaded, but then you DO have to make sure that it is threadsafe, and put a lock in there....

# re: Singleton with VS2005 snippet

Left by Simone at 8/12/2007 10:58 AM

Yes, but depends on what you have to do. When you don't want to explicitly deal with the multi-threading problem it's better to initialize in the static part so that the CLR and compiler handle the thread-safety by themselves.
Probably the most complete implementation of a Singleton (and most complex) is the one by Brad Abrams with double check locking and the use of System.Threading.Thread.MemoryBarrier (http://blogs.msdn.com/brada/archive/2004/05/12/130935.aspx), but do we really need so much safety?

Comments have been closed on this topic.