Mega Code Archive

 
Categories / C# Tutorial / Class
 

Static Fields

A static member can be accessed before any objects of its class are created. You can call a static member without referencing to any object. You can declare both static methods and static variables. Variables declared as static are, essentially, global variables. All instances of the class share the same static variable. A static variable is initialized when its class is loaded. A static variable always has a value. If not initialized, a static variable is initialized to zero for numeric values. If not initialized, a static variable is initialized to null for object references. If not initialized, a static variable is initialized to false for variables of type bool. using System; class MyClass {     public MyClass()     {         instanceCount++;     }     public static int instanceCount = 0; } class MainClass {     public static void Main()     {         MyClass my = new MyClass();         Console.WriteLine(MyClass.instanceCount);         MyClass my2 = new MyClass();         Console.WriteLine(MyClass.instanceCount);     } } 1 2