Wednesday, 19 August 2015

What is difference between instance constructor and Static constructor in C#.Net

Main Differences are :
  •  A Constructor declare using Static modifier was known as  Static Constructor. Rest of all were Instance Constructor.
  • Static Constructor are responsible for initialization of static variables and Instance Constructor for initialization of instance constructor.
  • A static constructor is called only one's in the execution of a class. Where as instance constructor gets called each time we create the object of the class. if no object is created. It is not called at all.
  • static constructor is the first block of which gets executed under the class.
  • A static constructor can't be parameterized because explicit calling of the constructor is not done.
Sample Example:

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

namespace ConsoleApplication1
    class staticconstructor
        static staticconstructor()
            Console.WriteLine("static constructor");
            Console.WriteLine("non-static constructor");
        static void Main()
            Console.WriteLine("main method");
            staticconstructor st = new staticconstructor();
            staticconstructor st1 = new staticconstructor();

Output :

No comments:

Post a Comment