Singleton with parameters

Singleton is ugly but…

public class Singleton 
{ 
    private static Singleton _instance = null; 

    private static Object _mutex = new Object();
 
    private Singleton(object arg1, object arg2) 
    { 
        // whatever
    } 
 
    public static Singleton GetInstance(object arg1, object arg2)
    { 
        if (_instance == null) 
        { 
          lock (_mutex) // now I can claim some form of thread safety...
          {
              if (_instance == null) 
              { 
                  _instance = new Singleton(arg1, arg2);
              }
          } 
        }

        return _instance;
    }
}  

Skeet blogged about this years ago I think, it’s pretty reliable. No exceptions necessary, you aren’t in the business of remembering what objects are supposed to be singletons and handling the fallout when you get it wrong.

Edit: the types aren’t relevant use what you want, object is just used here for convenience.

Leave a Comment