C Sharp/static Members

From Meshplex

Jump to: navigation, search
Image:Csharp_programming.gif

Home

Basics
Home
introduction
Overview
Statements
Data Types
Variables
Operators
Flow Control
Variables II
Functions
C# - Classes and Objects I

Dates and Times
Conversions

Advanced
Classes II
Inheritance
GUI
Namespaces
Exceptions
Threads
ADO.NET
Generics

[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.


  1. using System;
  2.  
  3. class Program
  4. {
  5. public class MyClass
  6. {
  7. private static int count = 0;
  8. public MyClass() //Default constructor
  9. {
  10. count++; //increment object creation
  11. }
  12. ~MyClass() //destructor
  13. {
  14. count--; //decrement object count
  15. }
  16. public int getCount //Property
  17. {
  18. get
  19. {
  20. return count;
  21. }
  22. }
  23. }
  24. static void Main(string[] args)
  25. {
  26. //create objects
  27. MyClass a = new MyClass();
  28. MyClass b = new MyClass();
  29. MyClass c = new MyClass();
  30.  
  31. //print amount of objects created
  32. Console.WriteLine("Object a returns: " + a.getCount);
  33. Console.WriteLine("Object b returns: " + b.getCount);
  34. Console.WriteLine("Object c returns: " + c.getCount);
  35.  
  36. //delete objects -- keep at least one object
  37. a = null;
  38. b = null;
  39.  
  40. //force garbage collector
  41. System.GC.Collect();
  42. System.GC.WaitForPendingFinalizers();
  43.  
  44. Console.WriteLine("Object count after cleanup: " + c.getCount);
  45. Console.Read();
  46. }
  47. }

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.