Thursday, October 30, 2008

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




No comments:

Post a Comment