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