Skip to content

Instantly share code, notes, and snippets.

@aalhour
Last active August 17, 2017 21:35
Show Gist options
  • Save aalhour/89e658dda972ec9deb4c to your computer and use it in GitHub Desktop.
Save aalhour/89e658dda972ec9deb4c to your computer and use it in GitHub Desktop.
A singleton class example in C#.
public sealed class SingletonExample
{
// internal singleton instance
private static SingletonExample _instance;
// lock for thread-safety laziness
private static readonly object _mutex = new object();
// private empty constuctor
private SingletonExample()
{
}
// public method, used to obtain an instance of this class
// implements double-locking
public static SingletonExample Instance
{
get
{
if (_instance == null)
{
lock (_mutex)
{
if (_instance == null)
{
_instance = new SingletonExample();
}
}
}
return _instance;
}
}
}
@ugreg
Copy link

ugreg commented Aug 17, 2017

so can use Instance in any class in the common namespace now?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment