Ad

Saturday, July 27, 2013

Static Constructors in C#.Net

Overview:
          In this article I would like to publish on "Static Constructors in C#.Net".



Description:
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.

Syntax of Creating a Static Constructors:


class hi
{
    // Static constructor
    static hi()
    {
        //...
    }
}

Static constructors have the following properties:

  1.  A static constructor does not take access modifiers or have parameters.
  2.  A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  3. A static constructor cannot be called directly.
  4. The user has no control on when the static constructor is executed in the program.
  5. 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.
  6.  Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
 Program:

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

namespace dt
{
    class Class4
    {
        static void Main(string[] args)
        {
            pnv o = new pnv();
            o.gg();
            Console.ReadLine();
        }
    }
    public class pnv
    {
        static pnv()
        {
            Console.WriteLine("This is Static Constructors:");
        }
        public void gg()
        {
            Console.WriteLine("This is a Method");
        }
    }
}

  OutPut:



No comments: