Possible Duplicate:
When to Use Static Classes in C#
Can someone please provide guidelines , standard checkpoints on when to create static class and when to create instance class.
Basically many a times I see while writing a code that the same thing could have been done using static class and methods and i get confused with many things.
So far i know below check points :
If object under the consideration can exists only once in entire application then it would come under "static"
If a method does not use any field variable inside it then it can be static method.
Static Classes are best used to create libraries of functions that will be called. Regular Classes are used to create objects that can be manipulated. It allows you to encapsulate the relations of a single bunch of code. Take, for instance, a point in Euclidian space. You could declare two floats and keep track of them individually, or you could use the following contract to declare how a point works.
This is a bit redundant, but it allows you to to write more readable code in the future - better keeping all your data encapsulated and well designed, making you a better programmer, because the equation of a line through two points goes from
to
Sorry the pseudocode is a bit Java informed. I have Java on the brain.
To my mind the best differentiator is state.
If your class has no state and is just a series of related methods that, when given an input, will give you an output then you have an excellent candidate for a static class.
If your class will be given input and then store it or in some other way will be expected to maintain its current state then you have a regular class.
Furthermore if your class is going to be declared
abstract
or is going to inherit behaviours from another class or implement behaviours from an interface, then you're moving away from a static class and have a normal class.In short:
Then you have a good chance it is a static class :)
I hope that helps.
NB (as per the astute comment below) state refers to the class storing some data that represents the current state-of-affairs for an object. Perhaps a class-level variable or a property.
if it should be a collection of functions, then you'd use static classes. like :
you can't say this on static classes:
because they can not be instantiated. They can only contain static members.
Taken from here.
but if it'd be a member of a code, like apple in a tree, you'd use instance classes. each apple would have its own characteristics but it doesn't change the fact that it is an apple. and it's a part of the tree which contains multiple instances of the apple.
etc.
You can look here.