Keep in mind that static variables are the equivalent to global variables - which are very very very bad!
I am afraid that is totally untrue. Static variables are not global, they can’t be used without reference to their class. They also can be made private for internal use only.
Static field are allocated once and shared between all instance because of their very own nature which was observed by the designer that they are static, meaning there is no need for each instance to maintain its own copy. This is not to say they are constants, the value of static member may or may not change during the life time of a program but the concept is; even if the value was changes, all remaining instance need to see the “same value”. Consider the type BankAccount which has – for the sake of argument – a static member GetCurrentInterestRate; if for any reason the GetCurrentInterestRate changed in one instance, all the others need to be informed with that change.
A more realistic example that we used befor is to maintain a shared variable between all instance that is incremented when a new object get created and decremented when any instance dies; this way, we can query any – still alive object or just the class name - for how many instance still alive. If we don’t have a mechanism to share this info between instance and non instances, we would need a higher level object just to maintain this information for us.
These were example of static members with dynamic nature, that is they are changing during their life time. Think of Int32.MaxValue as an example of a shared variable that is constant by nature (at least, on specific platform and microprocessor). You can argue that it is enough to define it constant. In this case you will loose the main advantage static keyword gives, you that is it is shared. If you have an array of one thousand integers, you will have one thousand 4 bytes (or 8000 or whatever happen to be the capacity of this type on a specific platform) instead of only 4 reserved for this MaxValue’s value and shared between all the thousand instances. That is not terribly efficient. Can you think of another easy way to solve this design problem without using the mighty key word static?
Walid Magd (MCP)
The primary challenge of every software development team is to engineer the illusion of simplicity in the face of essential complexity.
-Grady Booch