Search code examples
c#singletonstatic-class

Real life usage of Singleton and Static class c#


i do not want to know the difference between singleton and static class first of all. i like to know when people should use singleton class and when static class.

in my apps i use static class for helper or utility method and use singleton for db connection and error logger class. but with the help of static class can be used to return sql db connection object and as well as error logging system.

i really like to know about other senior developer where they use singleton class and where they use static class.

it will very helpful if some one discuss this matter with sample situation and sample code. thanks


Solution

  • A very broad question but will give you the first reason that popped into my head for use of a Singleton.

    A Singleton is more appropriate than a dedicated static class when you need to manage the lifetime of some cached objects. Singletons are perfect when you want to refresh state without having to worry about thread safety, for example if you have a class that is being used as a singleton and it has many cached properties or lists that incoming requests may want access to.

    The Refresh() method can simply be setting the current instance to a new instance and not having to refresh individual properties of the class:

    private static YourClass instance = new YourClass();  // first instance
    
    public static void Refresh(){
        instance = new YourClass();  // creates a new, refreshed instance while not needing to worry about thread safety
    }
    
    public static YourClass Instance{
          get{
             return instance;
          }
    }