Types are allowed to provided a distinguished method that is called when the type is first initialized. This type initializer is simply a static method with a well-known name(.cctor). A type can have at most one type initializer, and it must take no parameters and return no value. It is called automatically by CLR. The following shows a type initializer in C#:
namespace EssentialNet
{
public class Customer
{
public static string name;
static Customer()
{
name = "xiech2";
}
}
}
If a single C# type have both an explicit type initializer method and static field declarations with initializer expressions, .cctor method will begin with field initializers(in order of declaration), followed by the body of the explicit typer initializer method. Consider the following C# type definiation:
namespace EssentialNet
{
public class Customer
{
public static string name;
public static string id = "C1";
public static string code = "XIECH2";
static Customer()
{
name = "xiech2";
}
}
}
The fields will be initialized in the following order:id,code,name.
There is another distinguished method that CLR will call automatically each time an instance of the type is allocated. It is called a constructor and must have the distinguished name .ctor. The C# compiler will inject any non-static field initialization expressions in to the generated .ctor before the explicit method body. Consider the following C# type definition:
namespace EssentialNet
{
public class Customer
{
public static string name;
public static string id = "C1";
public static string code = "XIECH2";
public long t1 = DateTime.Now.Ticks;
public long t2 = DateTime.Now.Ticks;
public long t3;
static Customer()
{
name = "xiech2";
}
public Customer()
{
t3 = DateTime.Now.Ticks;
}
}
}
The fields will be initialized in the following order:t1,t2,t3.