Windows Phone Developers

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




Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

No comments:

Post a Comment