C#.NET : Static Constructor


The static constructor is used to initialize the "static data members", whereas the normal constructor (non-static constructor) is used to initialize the non-static data members.

Syntax :

 static classname()
  {
    //some code
  }

Rules :

  1. Static constructors can‘t contain any access modifiers.
  2. Static constructors can‘t be defined with arguments.
  3. Static constructors can‘t access the non-static data members.

Demo Program : Static Constructor

namespace StaticConstructorsDemo
{
  class MyCollege
   {
     //static fields
     public static string CollegeName;
     public static string Address;
     //static constructor
   
    static MyCollege()
    {
      CollegeName = "ABC College of Technology";
      Address = "Hyderabad";
    }
  }

  class Program
   {
    static void Main(string[] args)
     {
      Console.WriteLine(MyCollege.CollegeName);
      Console.WriteLine(MyCollege.Address);
      Console.Read();
     }
   }
}
0 Komentar untuk "C#.NET : Static Constructor"

Back To Top