Construction Questions


In this article we are going to discuss construction questions with examples in C#.

Can you create object of class with private constructor in C#?

No. In C#, you cannot directly create an instance of a class with a private constructor from outside the class.

Private Constructor in C#

Base class and Child class have Constructor Which one will be Called First, When Derived Class Object is Created?

When an object of a derived class is created in C#, the constructors are called in a specific order. The base class constructor is called first, followed by the derived class constructor. This ensures that the base part of the object is properly initialized before the derived part.

Example

Here's an example to illustrate the order in which constructors are called:

using System;

class BaseClass
{
    public BaseClass()
    {
        Console.WriteLine("Base class constructor called.");
    }
}

class DerivedClass : BaseClass
{
    public DerivedClass()
    {
        Console.WriteLine("Derived class constructor called.");
    }
}

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

Output

Constructor Question in C#

Constructor chaining in C#?

When you want to share initialization code among multiple constructors, you can do it using constructor chaining. In Constructor chaining,the constructor calls another constructor in its class using the this(). You can also explicitly call a specific base class constructor using the base keyword.

Example

using System;

class BaseClass
{
    public BaseClass()
    {
        Console.WriteLine("Base class default constructor called.");
    }

    public BaseClass(string message)
    {
        Console.WriteLine($"Base class parameterized constructor called with message: {message}");
    }
}

class DerivedClass : BaseClass
{
    public DerivedClass() : base("Hello from Derived Class")
    {
        Console.WriteLine("Derived class constructor called.");
    }
}

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

Output

Constructor Question in C#
Prev Next