what is mean by static constructor ? explain me with understanding example?

Recommended Answers

All 2 Replies

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();
}
}
}

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.