How to create and use Static Constructors in C# (.NET)

Static Constructors in .NET (C#)
Static constructors are called automatically to initialize the class before the first instance is created or any static members are referenced. They do not have any parameters and cannot be called directly.
class StatSample
{
static StatSample ()
{
Console.WriteLine("StatSample Initialized");
// Log the process start time
Write2Log(DateTime.Now.ToString());
}
public static void SayHello()
{
Console.WriteLine("Hello");
}
private static void Write2Log(String msg)
{
Console.WriteLine(msg);
}
}
The following code invokes the static constructor without any new operator or any explicit call
StatSample.SayHello();


image: https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjEwwoI3ZrYFzZgUBx2y91qQMAzGj-JyHjh-geGMVM01fJiJ0PAB0-q_AQkAfjnM4DEtYsg1Gnh_AX-ZGEl1M96I-Ycm5JnL4Td_kMZwFxHkfmdhrCwMMbfXc_DamSW3buejvbuv2tvjjZM/s400/dnd_StaticConstructors.JPG

Read more at http://dotnetdud.blogspot.com/2008/10/blog-post.html#ut1PzkLYKG7uf6t6.99

Comments

Popular posts from this blog

Query to get concurrent Program details with Parameter list and value set attached to parameter.

Japan Style: Architecture Interiors Design

AR and OM link in oracle apps / AR transaction and Sales Order join query