Leveraging the .NET Framework features (sealed class and read-only properties) to implement the Singleton pattern in a thread safe manner.

   

The Singleton Class

   

using System;

using System.Collections.Generic;

using System.Text;

   

namespace SingletonUsingDotNetFramework

{

//Create a sealed class so it cannot be derived

sealed class Singleton

{

private Singleton() { }

//Create a static - readonly instance of this class

public static readonly Singleton Instance = new Singleton();

private int InstanceCounter = 0;

//Public Method to increment the counter

public int NextValue()

{

InstanceCounter += 1;

return InstanceCounter;

}

}

}

   

   

The Client Form

   

private void button1_Click(object sender, EventArgs e)

{

//Calling the readonly instance NextValue method

MessageBox.Show(Singleton.Instance.NextValue().ToString());

//Create a reference to the readonly instance

Singleton _instance = Singleton.Instance;

//Calling the instance NextValue method

MessageBox.Show(_instance.NextValue().ToString());

}

   

How .NET Supports Singleton

   

  1. The Singleton is still created using Lazy initialization so it does not consume memory when the object is not needed.

       

  2. The Framework guarantees thread safety on static type initialization (no need for lock or double checks)