5 Comments

  • Why not use new() instead? Is there some reason you had to use reflection?

    Change your public class declaration to:
    public class Singleton where T :class, new()

    then change your _instance instantiation to:
    private static readonly T _instance = new T();

  • Hi David,
    what about my solution?

    public abstract class Singleton where T : class, new()
    {
    protected Singleton() { }
    private static readonly object _sync = new object();
    private static T _instance;
    public static T Instance
    {
    get
    {
    if (_instance == null)
    {
    lock (_sync)
    {
    if (_instance == null)
    _instance = new T();
    }
    }
    return _instance;
    }
    }
    }

    // usage sample:
    public class MyClass : Singleton
    {
    protected MyClass() {}

    // ...
    }


    Let me know!

  • Oups.... pls, remove my previous comment: it's sooooooooo bad!
    1) double-check locking is outdated :-)
    2) : where new() and protected paremeterless constructor???

    Maybe i was drunk!!!
    Sorry.

  • I figured I was missing some basic component of what you were trying to accomplish. Makes perfect sense now.

  • Ah - good point. Sorry I missed that.

Comments have been disabled for this content.