Static Constructor
In this chapter you will learn:
What is static constructor
Each type can have only one static constructor. static constructor can have no parameters and it is execuated per type not per instance. static constructor is called by C# when initializing the type or calling its static members. It can only have extern and unsafe modifier.
A static constructor is used to initialize variables that apply to a class rather than an instance.
using System;// ja v a 2 s . c o m
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.
The following code uses the static constructor to initialize the random generator.
using System;// j a v a 2 s.com
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 ja v a2 s . c om*/
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.
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Class