Real life usage of Singleton and Static class c#

Monday, May 12, 2014










Take the 2-minute tour ×

Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.


















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



























If you are creating loosely coupled system, then there is no way you can use static classes (because they cannot implement abstraction and cannot be injected). Static classes also very hard to mock, so it's not your choice if you are doing TDD or simple unit-testing. So, I use them only for dependencies which are not related to business requirements and should not be mocked. E.g. for logging. I also use static classes for extension methods if I cannot extend existing class, but want handy member-like API.


























I usually use singleton classes when I am creating a database access object. Where I can have the instance of the object anywhere inside an application.


I usually stay away from static classes, which the exception of an occasional loader class when loading particular assets.
















lang-cs









http://ift.tt/1gfvC0d