Static constructor and Instance constructor in a program

In this article, I will explain how we use static and instance constructor in c#.
  • 12039

Introduction

Static constructor will be invoked only once when the first instance of the class is created. We can use static constructor and instance constructor in a program, Both the constructors are invoked during creation of first instance in a program.

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Constructor

{

    class Test

    {

        public Test()

        { 

            Console.WriteLine("Instance  Constructor----My name is Sharma");

        }

        static Test()

        {

            Console.WriteLine("Static  Constructor-----My name is Rahul");

        }

    }

    class StaticConstructor

    {

        static void Main()

        {

            //Static Constructor and instance constructor, both are invoked for first instance.

            Console.WriteLine("-------------------For firstinstance---------------");

            Test T1 = new Test();

            //Only instance constructor is invoked.

            Console.WriteLine("-------------------For Second instance-----------------");

            Test T2 = new Test();

            Console.Read();

        }

    }

}

 

Output

Clipboard231.jpg

© 2020 DotNetHeaven. All rights reserved.