Monday 18 February 2013

Static Constructor Vs Non-Static Constructor

  • A Constructor that is defined using static keyword is a static constructor. Rest of the others are Non-Static only. 
  • Static Constructor is the first block of code which executes under a class where as Non-Static Constructor gets executed only after creating the object of class as well as each and every time the object of class is created.
  • In the life cycle of a class a Static Constructor gets called one and only one time whereas a Non-Static Constructor gets called either for zero(no objects are created) or n times (n objects are created).
  • A Static Constructor can never be parametrized because it is the first block of code that executes in a class and more over it is implicitly called and Non-Static constructors can be parametrized because they are explicitly called and we have a chance of sending values to the parameters.

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

namespace ConsoleApps
{
    class StatCon
    {
        static StatCon()
        {
            Console.WriteLine("Static Constructor Called");
        }
        public StatCon()
        {
            Console.WriteLine("Non-Static Constructor Called");
        }
        static void Main()
        {
            Console.WriteLine("Main Method Called");
            StatCon s1 = new StatCon();
            StatCon s2 = new StatCon();
            StatCon s3 = new StatCon();
            Console.ReadLine();
        }
    }
}

No comments:

Post a Comment