Skip to content

Instantly share code, notes, and snippets.

@butaji
Created October 27, 2011 18:39
Show Gist options
  • Save butaji/1320422 to your computer and use it in GitHub Desktop.
Save butaji/1320422 to your computer and use it in GitHub Desktop.
Sinlgeton<WTF>
public static class Singleton<T> where T : class
{
static volatile T _instance;
static object _lock = new object();
static Singleton()
{
}
public static T Instance
{
get
{
if (_instance == null)
lock (_lock)
{
if (_instance == null)
{
ConstructorInfo constructor = null;
// Binding flags exclude public constructors.
constructor = typeof(T).GetConstructor(BindingFlags.Instance |
BindingFlags.NonPublic, null, new Type[0], null);
if (constructor == null || constructor.IsAssembly)
// Also exclude internal constructors.
throw new InvalidOperationException(string.Format("A private or " +
"protected constructor is missing for '{0}'.", typeof(T).Name));
_instance = (T)constructor.Invoke(null);
}
}
return _instance;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment