Class constructors

  • Thread starter Thread starter Mujtaba Syed
  • Start date Start date
M

Mujtaba Syed

Does that runtime guarantee that my static constructor will complete
execution before I call any other static method of that class?

If not, what is the most efficient way of implementing this.

Thanks,
Mujtaba.
 
Yes the static constructor will be called only once upon the first call to
the class.

See code...
using System;

namespace StaticConstructor

{

/// <summary>

/// Summary description for Class1.

/// </summary>

class Class1

{

/// <summary>

/// The main entry point for the application.

/// </summary>

[STAThread]

static void Main(string[] args)

{

MyClass a = new MyClass();

a.ShowMessage();

MyClass b = new MyClass();

b.ShowMessage();

}

}

class MyClass

{

static MyClass()

{

Console.WriteLine("Constructor ran!");

}

public void ShowMessage()

{

Console.WriteLine("Message printed!");

}

}

}
 
You may also want to review section 17.1 of the C# Specification located
here:

http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf

which states briefly:
"The static constructor for a class executes at most once in a given
application domain. The execution of a static constructor is triggered by
the first of the following events to occur within an application domain:
* An instance of the class is created.
* Any of the static members of the class are referenced."

ShaneB
 
Back
Top