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

What's the difference between a static method and a non static method c#?

505


When should we use sealed class in c#?

496


Can abstract class have constructor c#?

470


Is c# front end or back end?

515


Why do we need collections in c#?

471






Define Virtual folder?

635


What is the reason behind the invention of c#?

637


Explain the differences between static, void and public in c#?

529


How is a strongly-named assembly different from one that isn’t strongly-named?

611


What is the use of return in c#?

490


Are tuples mutable c#?

492


How do I declare inout arguments in c#?

540


How to use delegates with events?

559


What is the purpose of dependency injection?

481


Is c# easier than c++?

537