.Net C# Singleton Pattern – Best Practice

What is the best practice way to implement the Singleton design pattern in C#? You might be surprised at the number of flawed examples there are out there; many of the articles I looked at were incorrect (some subtlely, some not so) and several were on high traffic, popular sites!

This excellent article by Jon Skeet not only discusses several ways not to do it, but also the correct way:

public sealed class Singleton

{

// Prevent compiler adding a default public parameterless constructor

private Singleton() {}

public static readonly Singleton Instance = new Singleton();

// Explicit static constructor instructs compiler

// NOT to mark type as ‘beforefieldinit’

// Remove this if you do not need to guarantee lazy instantiation

static Singleton() {}

}

The static constructor is only required if you want to guarantee lazy instantiation (which Jon explains here.)

See also this MSDN article from Feb 2002.

Perth .Net UG Meeting – 10th Jan 2007

We are starting the year with an exciting talk by David Lemphers on his explorations into .NET and Robotics, 5:30pm, Weds 10th Jan 2007.

Please note that this meeting will be held at the Microsoft offices, level 14, QV1 building, NOT at the new Excom venue. Look forward to seeing you there!

He is also presenting on SQL server to the SQL UG the following evening at Excom.

Chance Quotes

Nick Randolph tagged me a while ago as part of the ‘5-things’ tagging meme pervading the ‘blogosphere’. Try as I might, I couldn’t find 5 things about me that I thought others would be interested in knowing (sad, I know), so instead here’s a few quotes and food for thought from interesting people about chance:

Chance favours the prepared mind – Louis Pasteur.

I will study and get ready, and perhaps my chance will comeAbraham Lincoln

God does not play dice [with the universe] – Albert Einstein

Men are not prisoners of fate, but only prisoners of their own mindsFranklin D. Roosevelt

Fortune can, for her pleasure, fools advance, And toss them on the wheels of ChanceJuvenal (55 AD – 127 AD)

No victor believes in chanceFriedrich Nietzsche

A lie gets halfway around the world before the truth has a chance to get its pants onWinston Churchill

When a man is pushed, tormented, defeated, he has a chance to learn somethingRalph Waldo Emerson

Fortune knocks but once, but misfortune has much more patience – Laurence Peter

Great lives are the culmination of great thoughts followed by great actions – Peter Sinclair

Chance is always powerful. Let your hook be always cast; in the pool where you least expect it, there will be a fishOvid (43 BC – 17 AD)

The Churchill quote is a bit of an odd one out.