When static constructor is invoked?

Answer Posted / ganesh

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.

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

Is This Answer Correct ?    6 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

How do I declare a pure virtual function in c#?

662


What is inheritance c#?

583


What is difference between ilist and list?

565


What is a static in c#?

576


Can we inherit sealed class in c#?

549






How do you access a constant field declared in a class?

571


What is a service layer c#?

544


What is a property in c#?

556


What is expandoobject in c#?

556


Can you drink alcohol with a loop recorder?

583


What is a dimensional array?

538


What do you mean by parsing and how to parse a date time string in c#?

604


What is the role of the datareader class in ado.net connections?

596


What does exclamation mark mean c#?

632


What is thread and explain states of a thread in c#?

547