Playing Chicken With Common Sense

Generic C# Singleton goodness

 

Here is a Generic Singleton factory. Enjoy!

// this is the class for which I want to maintain a single instance
public class
MyClass
{
private MyClass()
{
// private constructor ensures that callers cannot instantiate an object using new()
}
}
// Singleton factory implementation
public static class Singleton<T> where T :
class
{
// static constructor, runtime ensures thread safety
static Singleton()
{
// create the single instance of the type T using reflection
Instance = (T)Activator.CreateInstance(typeof(T), true);
}

// serve the single instance to callers
public static T Instance { private set; get; }
}
class Program
{
public static void Main()
{
Console.WriteLine(Object.ReferenceEquals(Singleton<MyClass>.Instance, Singleton<MyClass>.Instance));
}
}
Usage: Singleton<ClassTypeName>.Instance
  • 0 Comments
  • E-mail
  • Kick it!
  • Shout it
  • Bookmark and Share

Comments

Control panel

RecentComments

Comment RSS