Static Fields : Static field : Class C# Examples


C# Examples » Class » Static field »

 

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);
        }
}
    
   
  
   



Output

1
2


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Class
» Static field