Static Constructor Vs Instance Constructor in C#

Static Constructor

A constructor declared using static modifier is a static constructor. A static constructor is use to initialize static data or to perform a particular action that need to be performed only once in life cycle of class. Static constructor is first block of code to execute in class. Static constructor executes one and only one time in life cycle of class. It is called automatically. Static constructor does not take any parameters. It has no access specifiers. It is not called directly.

Instance Constructor

Instance constructor is used to initialize instance data. Instance constructor is called every time when object of class is created. It is called explicitly. Instance constructor takes parameters. It has access specifiers.

Example

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. namespace StaticVsInstance  
  6. {  
  7.     class Program  
  8.     {  
  9.         static int A;  
  10.         int B;  
  11.         static Program()  
  12.         {  
  13.             Console.WriteLine("Static Constructor Executed");  
  14.             A = 10;  
  15.         }  
  16.         public Program(int b)  
  17.         {  
  18.             Console.WriteLine("Instance Constructor Executed");  
  19.             B = b;  
  20.         }  
  21.         private void Display()  
  22.         {  
  23.             Console.WriteLine("A = " + A);  
  24.             Console.WriteLine("B = " + B);  
  25.         }  
  26.         static void Main(string[] args)  
  27.         {  
  28.             Program P1 = new Program(20);  
  29.             Program P2 = new Program(30);  
  30.             P1.Display();  
  31.             P2.Display();  
  32.             Console.ReadKey();  
  33.         }  
  34.     }  
  35. }   

Output

Static Constructor Executed
Instance Constructor Executed
Instance Constructor Executed
A = 10
B = 20
A = 10
B = 30

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now