Constructor Chaining

Introduction

In this article, I am going to explain to you how to implement constructor chaining in C# Programming. This is one of the most common questions asked in C#.Net interviews.

C# Constructor

A constructor in C# is a member of the class. It is a special method in a class whose name should be the same with that class name. It is used to initialize the class data members. This constructor method will be executed when object of that class is created. Inside a class we can define multiple Constructors.

Creating Multiple Constructor in a Class

public class PritiTeckWorld
{
    public string Name;
    public int Age;
    public PritiTeckWorld()
    {
        Console.WriteLine("This is default");
    }
    public PritiTeckWorld(string Name,int Age)
    {
        this.Name = Name;
        this.Age = Age;
        Console.WriteLine("Name is:{0} and Age is:{1}",Name,Age);
    }
    static void Main(string[] args)
    {
        PritiTeckWorld obj=new PritiTeckWorld();
        PritiTeckWorld obj1= new PritiTeckWorld("Pritiranjan",35);
    }
}

Output

C# Constructor

Constructor Chaining

  • Calling a constructor from another constructor is called Constructor chaining.
  • If a constructor calls a current class constructor, then this keyword is used to identify the current class constructor.

Calling the current class constructor

public class PritiTeckWorld
{
    public string Name;
    public int Age;
    public PritiTeckWorld():this("Pritiranjan",354)
    {
        Console.WriteLine("This is default constructor");
    }
    public PritiTeckWorld(string Name,int Age)
    {
        this.Name = Name;
        this.Age = Age;
        Console.WriteLine("Name is:{0} and Age is:{1}",Name,Age);
    }
    static void Main(string[] args)
    {
        PritiTeckWorld obj=new PritiTeckWorld();
    }
}

Output

Calling current class constructor

  • If a constructor calls the base class constructor, then the base keyword is used to identify the base class constructor.

Calling base class constructor

public class Employee
{
    public string Name;
    public int Age;
    public Employee(string Name, int Age)
    {
        this.Name = Name;
        this.Age = Age;
        Console.WriteLine("Name is:{0} and Age is:{1}", Name, Age);
    }
}
public class PritiTeckWorld:Employee
{
    public PritiTeckWorld():base("Pritiranjan",35)
    {
        Console.WriteLine("This is default constructor");
    }
    static void Main(string[] args)
    {
        PritiTeckWorld obj=new PritiTeckWorld();
    }
}

Output

Calling base class constructor

Note: In both cases, first, the calling constructor will invoke.

Summary

In this article, I discussed how we can create multiple constructors in C# programming. We also saw how we can implement constructor chaining in both the current class and the base class.


Similar Articles