Constructor and Destructor – C# Programming Questions – Real

This section contains technical C# programming interview questions on constructor and destructor with answers and explanation asked in technical interviews for freshers and experienced.

Topic – Constructor and Destructor, Static Constructor in C#, Private constructors etc.


Q- What is output of the following program? When we create 2 objects of the class A e.g.

A obj1 = new A();
A obj2 = new A();

class A
{   
    static A()//Static constructor
    {
        Console.WriteLine("Static Constructor");
    }

    public A()// Constructor
    {      
        Console.WriteLine("Class Constructor");
    }    
}

Answer:

Output:

Static Constructor
Class Constructor
Class Constructor

Explanation: If we have static constructor in a class, it will be called before class constructor when we create first object of the class.

Static constructor will be called only once i.e. on first object creation and will not be called even we create multiple objects afterwards.

That’s the reason, in the output Static Constructor is called on first object creation.




3 thoughts on “Constructor and Destructor – C# Programming Questions – Real”

    • Thanks for the good question Nikul. The answer has been updated and elaborated more with notes for the question “Q- On execution of B b = new B();statement, what will be order of constructor call?”
      You need to use “base( some argument)” in derived class constructor e.g. public B():base(5) explicitly to call parameterized constructor.

      Reply

Leave a Comment