Search This Blog

Tuesday, December 18, 2012

Static Constructors C#

C# > Class > static constructor

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.

Static constructors have the following properties:

  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

  • A static constructor cannot be called directly.

  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
     public class Log
    {
         // Static constructor:
         static Log()
        {
            System.Console.WriteLine("The static constructor invoked.");
         }
         public static void Write(string text)
        {
           System.Console.WriteLine("The Write method invoked.");
        }
   }
   class Program
   {
       static void Main(string[] args)
      {
          Log.Write("text"); // constructor invoked
          Log.Write("text"); // constructor not invoked.
      }
  }
}