Thursday, June 16, 2011

Static class vs static member vs Singleton

Static class vs Static members


Static Class
Not Static Class with All Static Methods
1.        
This version can’t have instance constructor, and hence we can’t create object of static class. they can contain a static constructor.
This version has constructors and we can create object of this class.
2.        
We can’t pass this class as argument of the method.
We can pass this object as argument.
3.        
You can’t inherit another class in static class.
You can inherit another class.
4.        
Static class can’t be inherited.
This version can be inherited in another class.
5.        
All method and fields inside this call must be static.
Not necessary to make all fields/methods to be static. Though C# does not support static local variables.
6.        
Static class cannot implement interface.
This version can implement interface.
7.        
Method is static class can’t be virtual.
Static method can’t be virtual, we can’t override them.  Static methods can be overloaded but not overridden.
8.        
Use static class to group methods which are not associated with particular objects, for example, we can use static class for utility methods or methods which behaves like fire and forgot.
Use this version, when your method needs to be used as utility method inside the class, for some internal processing.
9.        
The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added.
It is more typical to declare a non-static class with some static members, than to declare an entire class as static. Two common uses of static fields are to keep a count of the number of objects that have been instantiated, or to store a value that must be shared among all instances.

Static class vs Singleton
Though both have single instance throughout the application, we can create instance of the singleton instance and can pass it as object in the method, as a result you can use singleton object as normal. This is the huge advantage of singleton over the static class.