C# Static Constructors

Description

A static constructor executes once per type, rather than once per instance.

A type can define only one static constructor, and it must be parameterless and have the same name as the type.

Syntax

The following class creates a static constructor.


class ClassName /*from  ww w.j  a v a2 s .com*/
{ 
   static ClassName() {
    ...
   } 
} 

Example


using System;//from  w ww .  j  a  v a 2  s  .c  om

class MyClass
{
    static MyClass()
    {
        Console.WriteLine("MyClass is initializing");
    }
    public static int I;
}

class MainClass{
    public static void Main()
    {
        MyClass.I = 1;
    }
}

The code above generates the following result.

Note

The runtime automatically invokes a static constructor just prior to the type being used. Two things trigger this:

  • Instantiating the type
  • Accessing a static member in the type

Static field initializers run just before the static constructor is called.

The following code uses the static constructor to initialize the random generator.


using System;/*from   w ww. ja v a  2s  .c  o  m*/

class MyClass
{
   private static Random RandomKey;

   static MyClass()                     
   {
      RandomKey = new Random();                   
   }

   public int GetValue()
   {
      return RandomKey.Next();
   }
}

class Program
{
   static void Main()
   {
      MyClass a = new MyClass();
      MyClass b = new MyClass();
      Console.WriteLine("Next Random #: {0}", a.GetValue());
      Console.WriteLine("Next Random #: {0}", b.GetValue());
   }
}

The code above generates the following result.

The following code uses the static constructor to initialize static variables.


using System; //from   ww  w  . jav  a  2  s . com
 
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); 
  } 
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor