Use a static constructor. : static field « Class « C# / CSharp Tutorial






using System; 
 
class Cons { 
  public static int a; 
  public int b; 
 
  // static constructor 
  static Cons() { 
    a = 99; 
    Console.WriteLine("Inside static constructor."); 
  } 
 
  // instance constructor 
  public Cons() { 
    b = 100; 
    Console.WriteLine("Inside instance constructor."); 
  } 
} 
  
class MainClass { 
  public static void Main() {   
    Cons ob = new Cons(); 
 
    Console.WriteLine("Cons.a: " + Cons.a); 
    Console.WriteLine("ob.b: " + ob.b); 
  } 
}
Inside static constructor.
Inside instance constructor.
Cons.a: 99
ob.b: 100








7.44.static field
7.44.1.Static Fields
7.44.2.Use a static field to count instances.
7.44.3.Use a static constructor.
7.44.4.Reference Static Field without Instance
7.44.5.Static field init
7.44.6.Reference a static member variable without using the class name
7.44.7.Instance Counting