Static constructor in C#

In this article, we will learn about static constructor in C#.
  • 3958

Introduction

Static constructor is a special method that called before when the first object of the class is created. Static constructor is used to initialize only static data.

Some important points about static constructor

  • It is used to initialize static data members.
  • A static constructor does not take access modifiers.
  • A static constructor can not have parameters.
  • A static constructor cannot be called directly.
  • The user has no control on the static constructor is executed in the program.

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Constructor

{

    class Test

    {

        static Test()

        {

            Console.WriteLine("My name is Rahul");

        }

    }

    class StaticConstructor

    {

        static void Main()

        {

            //Static Constructor is invoked for first instance.

            Test T1 = new Test();                

            Console.Read();

        }

    }

}

 

Output 

 Clipboard230.jpg

© 2013 dotNetheaven. All rights reserved.