DEEPAK GARG

1.why static constructor executes at most one time during a single program instantiation.

2. when to use static constructor some real-time application example

with regards

Deepak Garg



Re: Visual C# Language C# Programming->static constructor

Mark Betz

Static constructors bother me :). Well, not actually, but the idea of a constructor that initializes the _class_ as opposed to one that initializes an instance of the class can be quite confusing. It's one of those features that I am not convinced has a bunch of value. Static properties in my view should be initialized at the point of definition, but I am probably being a C++ bigot.

Anyway, as to your question. The point of static members is that they are atributes of the class, and accessible using the class name without having any instance of the class. I'll give you an example from ASP.NET. There is a class called HttpContext, and it has a static property Current that always contains the context for the current request. So you can always refer to HttpContext.Current to obtain the current request context, which is an instance of HttpContext.

Another case where you often see static properties is in the case of a singleton, a class that is intended to have one and only one instance. Suppose you had...

public sealed class Earth
{
private Earth() { // do something }; // <--- private constructor, so you can't create one of these in code

private int _population;
public int Population
{
get { return _population; }
set ( _population = value; }
}

public static Earth TheEarth() { return _earth; }; // <--- the only way to get one of these

private static Earth _earth = new Earth(); // <--- created at startup when the assembly is initialized
}

int currentPopulation = Earth.TheEarth.Population;

Actually, in this simple example it would make more sense to make Population static as well, so you could just reference Earth.Population. A singleton (where you actually create a single instance of the class) makes sense in the case where the object has significant initialization, or where the class itself isn't semantically a singleton, but treating it as one makes sense in the current context. The idea of a static constructor makes the initialization question mostly moot, since you can now use a static constructor to perform initialization of static members. However, there are some limits on static constructors. They cannot take parameters, you have no control over when they are executed, and of course they cannot access non-static members of the class.

Hope this helps. It can be kind of confusing, but I think the simplest explanation to fall back on is "static members are attributes of the class, not an instance of the class."