.NET Singletons 21 January 2005 at 00:00

Singleton classes are useful when you only want one possible instance of a classs to be running for your application. A good example is a settings - where you want to be sure that settings are not overwritten if more than one class has write access to those settings.

However, exposing the standard access method is NOT thread-safe - you need to add synchronisation to the class to ensure that only one instance is ever returned. This can be done as follows:

using System;

namespace YourNamespace {

  /// <summary>
  /// Singleton class for retrieving application settings.
  /// </summary>
  public class Settings {

    private static Settings settings = null;
    private static Object syncLock = new Object();

    private Settings() {
      // constructor tasks done here

    /// <summary>
    /// Access method for singleton implementation.
    /// </summary>
    /// <returns>An instance of the singleton.</returns>
    public static Settings Access() {
      lock (syncLock) {
        if (settings == null) {
          settings = new Settings();
      return settings;

Note that a dummy object is locked each time the method is accessed to ensure that synchronisation issues do not occur. There are other ways of doing this, but this is the simplest, and far as I know, safest way.

Standard T-SQL transaction template 21 January 2005 at 00:00

  -- do updates etc 

  IF @@ERROR <> 0