C#: Singleton pattern with quick code snippet
Objective
Singleton pattern provides a global, single instance by making the class create a single instance of itself.
Allowing other objects to access this instance through a class method that returns a reference to the instance. A class method is globally accessible.
Singleton Class Code Snippet
Declaring the class constructor as private so that no other object can create a new instance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace singleton
{
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
static int instanceCounter;
private Singleton() {
}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
public int getCounter()
{
return instanceCounter++;
}
}
}
Calling class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace singleton
{
class Program
{
static void Main(string[] args)
{
var counter = Singleton.Instance;
var test = counter.getCounter();
}
}
}