3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by __avd
0

Static constructors allow you to initialize [static] members in a static class when the class is referenced.

A very detailed article has been posted at:
http://www.c-sharpcorner.com/UploadFile/cupadhyay/StaticConstructors11092005061428AM/StaticConstructors.aspx

The example provided is:

using System;
namespace Constructor
{
class Test1
{
private static int id ;
//Static constructor, value of data member id is set conditionally here. 
//This type of initialization is not possible at the time of declaration.
static Test1()
{
if( Test.Id < 10 )
{
id = 20;
}
else
{
id = 100; 
}
Console.WriteLine("Static<Class> Constructor for Class Test1 Called..");
}
public static void print()
{
Console.WriteLine("Test1.id = " + id);
}
static void Main(string[] args)
{
//Print the value of id 
Test1.print();
}
}
}
0

Static constructor is not inherited and cannot be called directly. Access modifier are not allowed with static constructor. The static constructor for a class execute at most once in a given application domain.

The execution of static constructor is triggered by the first of the following events to occur within an application domain:

1. An instance of the class is created.
2. Any of the static member of the class is accessed/referenced.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.