C# Constructor Chaining

C# Code Snippets Constructor Chaining
Share:

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; }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger