Kevin Spencer said:
Static methods are useful when you dont' need access to any member in the
class in which the methods are created. The reason for this is simply saving
memory. An instance method is a method which is included in an instance of a
class. When the class is instantiated, a copy of the class is placed on the
stack. This means that, for every copy of the class, a copy of the method is
created. A static method remains in the heap; there is only one instance of
it. So, if the method does not need to access any instance members of the
class, it can be a static method, and save memory. It *can* access other
static members of the class, or any other static members of any class that
is accessible to it.
--
HTH,
Kevin Spencer
Microsoft MVP
..Net Developer
You can lead a fish to a bicycle,
but it takes a very long time,
and the bicycle has to *want* to change.
All Objects of a Class Share Just One Copy of Each Instance Method
Because each instance method is executed in relation to a specific object,
it seems that there exists one particular instance method copy in the memory
per object. However, this is not the case, because it would consume far too
much memory. Instead, all objects of the same class share just one copy of
each instance method.
The Rocket class shown next illustrates this point. Two Rocket objects are
created and their references assigned to rocketA and rocketB, respectively
(lines 30 and 31). Even though there is only one copy of the Launch method,
rocketA.Launch() (line 40) still executes Launch in relation to rocketA, and
rocketB.Launch() (line 41) executes Launch in relation to rocketB.
01: class Rocket
02: {
03: private double speed;
...
10: public void Launch()
11: {
...
15: speed = 3000.9;
...
20: }
...
25: }
30: Rocket rocketA = new Rocket();
31: Rocket rocketB = new Rocket();
40: rocketA.Launch();
41: rocketB.Launch();
How can C# make this possible? The compiler secretly passes the reference of
the object for which the method is called along as an argument to the
instance method. If you could look down into the engine room of the compiler,
it might look like the following lines:
Rocket.Launch (rocketA);
Rocket.Launch (rocketB);
The compiler then (also secretly) attaches the object reference to any code
inside the method that is specific to the object. For example, during the
Rocket.Launch(rocketA) call, the following line
speed = 3000.9
becomes equivalent to
rocketA.speed = 3000.9