C# Static Constructors
In this chapter you will learn:
- What are C# Static Constructors
- How to create a static constructor
- Example
- Note for 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 w w w . j a v a 2s .c o m
{
static ClassName() {
...
}
}
Example
using System;// w w w.j a va 2s.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.
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;//w w w . j av a 2 s . 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. j ava 2 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: