A static constructor is called before the first object is created. - CSharp Custom Type

CSharp examples for Custom Type:Constructor

Introduction

It is called only once and then is never used again.

Demo Code

using System;/*from ww w . j  av a2s .c o  m*/
public class test
{
   static public int si;
   public int i;
   public void routine()
   {
      Console.WriteLine("In the routine - i = {0} / si = {1}\n", i, si );
   }
   static test()
   {
      si = 100;
      Console.WriteLine("In Static Constructor - si = {0}\n", si );
   }
   public test()
   {
      i++;
      si++;
      Console.WriteLine("In Constructor- i = {0} / si = {1}\n", i, si );
   }
}
class TestApp
{
   public static void Main()
   {
      Console.WriteLine("Start of Main function...");
      Console.WriteLine("Creating first object...");
      test first = new test();
      Console.WriteLine("Creating second object...");
      test second = new test();
      Console.WriteLine("Calling first routine...");
      first.routine();
      Console.WriteLine("Creating third object...");
      test third = new test();
      Console.WriteLine("Calling third routine...");
      third.routine();
      Console.WriteLine("Calling second routine...");
      second.routine();
      Console.WriteLine("End of Main function");
   }
}

Result


Related Tutorials