About
In this code snippet, we learn how to chain constructors in C#.
Constructors are methods meaning you can overload them. Overloading can lead to code duplication. We can use chaining to get rid of the code duplication. Instead of implementing duplicate code in the overloaded method we can just call the previous method. This process is called chaining.
Constructors can be chained by adding this code: : this (method signiture) after the method head. In the example above where it says “method signature” you put the input parameters that were passed to your overloaded method to act as arguments for your original method.
Let’s look at the code example below to see how to chain constructors.
Code:
using System; namespace ConstructorChaining { class Program { static void Main(string[] args) { //Here => MyClass(10) we are calling the constructor method and passing it a parameter(argument). MyClass MC = new MyClass(10, "Hello."); Console.WriteLine("Prop1: " + MC.MyProperty1 + " Prop2: " + MC.MyProperty2); Console.ReadLine(); } } class MyClass { public MyClass(int setMyProperty) { MyProperty1 = setMyProperty; } //As you can see we can overload the constructor just like any other method. //But now we might have a problem with having duplicate code. /* public MyClass(int setMyProperty1, string setMyProperty2) { //Code duplication. MyProperty1 = setMyProperty1; MyProperty2 = setMyProperty2; } */ //To avoid code duplication we can implement constructor chaining. //The setMyProperty1 input parameter will be passed to the other method as a parameter. //MyClass(int setMyProperty1, string setMyProperty2) ==> : this(setMyProperty1) //The : this(setMyProperty1) signiture must match up with the version of the method you want to call. //In our case that is the method above. public MyClass(int setMyProperty1, string setMyProperty2) : this(setMyProperty1) { //MyProperty1 = setMyProperty1; MyProperty2 = setMyProperty2; } public int MyProperty1 { get; set; } public string MyProperty2 { get; set; } } }