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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace StaticVsInstance
- {
- class Program
- {
- static int A;
- int B;
- static Program()
- {
- Console.WriteLine("Static Constructor Executed");
- A = 10;
- }
- public Program(int b)
- {
- Console.WriteLine("Instance Constructor Executed");
- B = b;
- }
- private void Display()
- {
- Console.WriteLine("A = " + A);
- Console.WriteLine("B = " + B);
- }
- static void Main(string[] args)
- {
- Program P1 = new Program(20);
- Program P2 = new Program(30);
- P1.Display();
- P2.Display();
- Console.ReadKey();
- }
- }
- }
Output
Static Constructor Executed
Instance Constructor Executed
Instance Constructor Executed
A = 10
B = 20
A = 10
B = 30