what is a static constructor?

Posted by Rajendra.prasad under C# on 5/16/2010 | Views : 1370 | Status : [Member] | Replies : 2
Hi All,
what is a static constructor?

Regards,
Rajendra




Responses

Posted by: Raja on: 5/16/2010 [Member] Starter

Up
0
Down
Static Constructor: It is used for initializing only the static members of the class. These will be invoked for the very first time the class is being loaded on the memory. They cannot accept any arguments. Static Constructors cannot have any access modifiers.

Look at this http://www.dotnetfunda.com/interview/exam4-what-is-static-constructor-.aspx
http://www.dotnetfunda.com/articles/article587-discussing-constructors-in-csharp-.aspx
Or http://www.dotnetfunda.com/interview/exam1721-what-are-the-various-types-of-constructors.aspx
Above definition has been taken from the last link.

Thank you.

Regards,
Raja, USA

Rajendra.prasad, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Er.deepakdalal on: 5/19/2010 [Member] Starter

Up
0
Down
Static Constructors :- A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.

class SimpleClass
{
// Static constructor
static SimpleClass()
{
//...
}
}

Static constructors have the following properties:

A static constructor does not take access modifiers or have parameters.

A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

A static constructor cannot be called directly.

The user has no control on when the static constructor is executed in the program.

A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

Example
In this example, the class Bus has a static constructor and one static member, Drive(). When Drive() is called, the static constructor is invoked to initialize the class.

public class Bus
{
// Static constructor:
static Bus()
{
System.Console.WriteLine("The static constructor invoked.");
}

public static void Drive()
{
System.Console.WriteLine("The Drive method invoked.");
}
}

class TestBus
{
static void Main()
{
Bus.Drive();
}
}

Rajendra.prasad, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response