[edit] Static Members
A static variable is a regular variable in a class. The only difference is is that a static variable value stays the same across all objects. It also can be accessed by all objects that is associated with a class. So through out the whole class each object contains a copy of the static variable. You declare a static variable like this:
public class MyClass
{
private static int StaticVar = 0;
}
Even though the static variable may seem global to the whole program but in actuality it is only accessible classwide.
- Performance Consideration - Using static variable can conserve memory. So when only one copy of a variable is enough use the static keyword.
Any object created using the MyClass class will have a copy of all static variables in the class. It is also recommended that you only access static members by public methods such as properties.
[edit] Static Example
This program will keep track of how many objects are created. Then it will display the amount of objects created.
using System; class Program { public class MyClass { private static int count = 0; public MyClass() //Default constructor { count++; //increment object creation } ~MyClass() //destructor { count--; //decrement object count } public int getCount //Property { get { return count; } } } static void Main(string[] args) { //create objects MyClass a = new MyClass (); MyClass b = new MyClass (); MyClass c = new MyClass (); //print amount of objects created Console.WriteLine("Object a returns: " + a.getCount); Console.WriteLine("Object b returns: " + b.getCount); Console.WriteLine("Object c returns: " + c.getCount); //delete objects -- keep at least one object a = null; b = null; //force garbage collector System.GC.Collect(); System.GC.WaitForPendingFinalizers(); Console.WriteLine("Object count after cleanup: " + c.getCount); Console.Read(); } }
Output
Object a returns: 3
Object b returns: 3
Object c returns: 3
Object count after cleanup: 1
As you can see there are 3 objects created and the default constructor is called automatically when each object is created. When the default constructor is called it increments the count static variable
The garbage collector at lines 41-42 will force the garbage collector to execute. Line 42 will wait for the garbage collector to finish its task.
|