C# class and constructor – programs for practice

Q) What is output of C# code?

class Base
{
    public Base()
    {
        Console.WriteLine("Base class constructor");
    }
}
class Child : Base
{   
    public Child()
    {
        Console.WriteLine("Child class constructor");
    }

}
class Program
{
    static void Main(string[] args)
    {
        Child c = new Child();
    }
}

[su_spoiler title=”View Answer” style=”fancy” icon=”folder-2″] Output:
Base class constructor
Child class constructor
Explanation: In inheritance C# oops relationship, when we create object of a derived or child class then first base class constructor then derived class constructor get called.
[/su_spoiler]

Q) What is output of below C# code example?

class A
{
    static A()
    {
        Console.WriteLine("Static A()"); 
    }
    
    public A() { 
        Console.WriteLine("A()"); 
    }   
}

class Program
{
    static void Main(string[] args)
    {
        A obj = new A();       
    }
}

 

Output:

  1. Compiler error – constructor re-definition
  2. Compiler error – constructor cannot be static
  3. Will print A()
  4. Will print Static A()then A()
[su_spoiler title=”View Answer” style=”fancy” icon=”folder-2″] Answer: D
Explanation: if a class have static constructor then on creation of an object of the class static constructor will be called then class constructor.
[/su_spoiler]


Leave a Comment