Click here to Skip to main content
15,885,953 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When we can do the same thing using static classes, why do we need singleton?

I researched a lot but couldn't understand the basic difference. Can somebody explain me in simple words with examples.

Thanks
Dinesh

What I have tried:

google searched but couldnt understand from the explanations
Posted
Updated 16-Feb-17 2:53am

Using singletons it is easier to control when the class is initialised to use things like lazy-initialisation etc. Using static classes you're pretty much get what you're given, your class is initialised on creation. Also using sigleton your ultimate class is still an object rather than a static class so has the advantages that come with that, ie it can be used in unit tested easier, use OO features like inheritance, can be passed as an object to other methods, store state etc.
 
Share this answer
 
Comments
Nathan Minier 16-Feb-17 7:38am    
It might also be worth noting that Singletons infer (though do not guarantee) a certain degree of thread safety, while static classes do not.
F-ES Sitecore 16-Feb-17 8:16am    
Not sure I'd agree with that really, either can be made thread safe or not depending on how you code them. The framework guarantees the static constructor will be thread safe, but as for the methods it is down to how you code them, as it would be for singleton too, only with the singleton you are sometimes relying on your own code to ensure thread safe initialisation rather than the guarantees the framework provides.
Nathan Minier 16-Feb-17 8:21am    
That's fair, and we can agree to disagree.

If I label anything a singleton, though, I'm going to enforce thread safety on it so downstream developers don't get a nasty surprise. A static item, though? Pure wild west.
F-ES Sitecore 16-Feb-17 8:26am    
Um...thread safe static constructors are guaranteed by the .net framework. You think your own code is more reliable than the framework? Maybe you should get a job at Microsoft then :)
Nathan Minier 16-Feb-17 8:27am    
Not construction, methods.
 
Share this answer
 
v2
Comments
Karthik_Mahalingam 16-Feb-17 22:25pm    
5
Maciej Los 17-Feb-17 3:21am    
Thank you, Karthik.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900