Thursday, 29 September 2016

Static Constructor


Static Constructor : The constructor was introduced for C#. This is a special constructor and gets called before the first object is created of the class, it is use to instantaneities some static data.It is access by only static member.Statis constructor do not accept any parameter.

public class myClass
{
    protected static readonly DateTime instanceCreateTiem;
    public myClass()
       {
              //
              // TODO: Add constructor logic here
              //
       }

    //Static constructor
    static myClass()
    {
        instanceCreateTiem = DateTime.Now;

         // The following statement produces the first line of output,
         // and the line occurs only once.
         Console.WriteLine("Static constructor sets  start time to {0}",
             instanceCreateTiem.ToLongTimeString());
     }
}


//I am creating an instance of a class
//costrutorr automaticall called
myClass obj = new myClass();

In the console you will get like
Static constructor sets  start time to 12/03/2009 00:10:20:20
Which shows that static constructor works as designed by Microsoft.

The main use of static constructor to initialized some static fields to perform some specific purpose only.

No comments:

Post a Comment

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...