1000 C# Facts(Static Constructor) Part-1

Static Constructor


In this lesson we will learn key facts about static constructor.


"Static constructor is used to initialize static data members when class is referenced for the first time means static constructor will not call from the second object creation on the class." 


Example on how to create static constructor and when it calls during program execution.



   public class Program
   {
        // Static Constructor
        static int art = 10;
        static Program()
        {
            Console.WriteLine("I am from Static Constructor");
        }
        // Default Constructor
        public Program()
        {
            Console.WriteLine("I am from Default Constructor");
        }  
        static void Main(string[] args)
        {
           // Both Static and Default constructors will invoke for first instance
            Program obj1 = new Program();

           // Only Default constructor will invoke
            Program obj2  = new Program();

            Console.WriteLine("\nPress Enter to Exit.");
            Console.ReadLine();
            Console.Read();
        }
    }


Why we cannot overload the static constructor ?

Ans: Overloading is not possible without passing the parameter. So in simple tern if we cannot pass the parameters to the Static constructors then we can’t overload it.

Why static constructor does not take access modifiers ?

 Ans: Because it is automatically run and you can not control or call it explicitly.

Key Facts:

  • Static constructor executes at most one time before any instance of the class.
  • Static constructor does not accept any parameters and access modifiers.
  • We don’t have control over static constructor execution, it is invoked by CLR.
  • We can create only one static constructor in a class. 

1 comment:

  1. You have given good clarity about static construtor. I wish you to put more useful .

    ReplyDelete

In case of any query , please let me know, Thanks