I was thinking about the classic issue of lazy singleton initialization - the whole matter of the inefficiency of:
if (instance == null)
{
instance = new
The best method I have found of creating a singleton is this:
public class Singleton
{
static public Singleton Instance { get; } = new Singleton();
private Singleton() { ... }
}
It is very concise, and more importantly, is also thread safe, which can be very troublesome to detect and fix as an application matures.
Update: To show it is lazy...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SingletonTest
{
class MySingleton
{
static public MySingleton Instance { get; } = new MySingleton();
private MySingleton() { Console.WriteLine("Created MySingleton"); }
public void DoSomething() { Console.WriteLine("DoSomething"); }
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting Main");
MySingleton.Instance.DoSomething();
}
}
}
Output:
Starting Main
Created MySingleton
DoSomething