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
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.
We can’t pass this class as argument of the method.
We can pass this object as argument.
You can’t inherit another class in static class.
You can inherit another class.
Static class can’t be inherited.
This version can be inherited in another class.
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.
Static class cannot implement interface.
This version can implement interface.
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.
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.
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.