Search code examples
c#inheritanceconstructoroverloadingchaining

Beginner to C#: How to do constructor chaining, overriding and using :this / :base?


I've studied Java last year and I don't think I ever had issues with writing constructors. I'm unfortunately so confused at how overloading and chaining in C# works, or even the basic concept of it.

I've seen :base get used in inheritence, but I'm not sure how. I've seen :this get used in many places, and it always boggles me why it's used.

Here's an example of some code with :this (made public variables without setters/getters for sake of argument).

public class Person
{
    public string firstName;
    public string lastName;
    public string height;
    public int age;
    public string colour;

public Person():this("George", "Seville", "45cm", 10, "Black")
    {
    // This is the default constructor, and we're defining the default 
values.
     }

public Person(string firstName, string lastName, string height, int age, 
string colour)
    {
        this.firstName = firstName;
        this.lastName = lastName;
        this.height = height;
        this.age = age;
        this.colour = colour;
    }

}}

I can only understand how the first constructor is being used e.g. making a simple object of "Person" would give it the default values. That's as far as I can understand. This code is unfinished since it shows 2 default constructors. I'd like to be able to overload and chain for every variant available i.e. 1 parameter, 2 parameter... so they all overload and chain appropriately.

So it should kind of (might not be right) look like this:

public Person():this("George", "Seville", "45cm", 10, "Black")
    {
    // This is the default constructor, and we're defining the default 
values.
     }

public Person(string firstName):this(firstName, "George", "Seville", "45cm", 
10, Black)
    {
        this.firstName = firstName;
    }

public Person(string firstName, string lastName):this(firstName, lastName, 
"Seville", "45cm", 10, Black)
    {
        this.firstName = firstName;
        this.lastName = lastName;
    }

Of course I'm not sure if any of the code above makes sense, but I've seen some Classes with constructors with :this for each of them, and each constructor links to the one below it until the user can create an Object with any combination of parameters defined.

As for :base, this completely confuses me. Here's an example I've actually found online:

    public class Circle:Shape
{
    public Circle():this(Color.Black, new Point(0,0), 1)
    {
    }

    public Circle(Color Colour, Point Position, double Radius):base(Colour, 
Position) 
    {
        this.Radius = Radius;
    }

I think :base refers to the parent class, but I'm not sure why and how. Also, why is :this being used in the first constructor and not :base?

There are the 2 aspects I'm very confused with. Using :this and :base and understanding exactly how constructor chaining and overloading works. Please let me know if my question is too abstract. I've tried to be as specific as possible.

Thank you all so much for your support and time. Much appreciated!


Solution

  • I'll try to explain it as simple as I can.

    Constructor overloading

    Nothing new here, it's just like overloading any other method - You simply need the same name but a different signature (meaning different parameters passing into the constructor).

    Constructor chaining

    This is done by using the keyword this - just like in the code samples in your question.
    btw, I usually use it to go from the most elaborate constructor to the simplest one.
    sample code:

    public class Person
    {
        public Person()
        {
            Children = new List<Person>();
        }
    
        public Person(string firstName)
            : this()
        {
            this.FirstName = firstName;
        }
    
        public Person(string firstName, string lastName)
            : this(firstName)
        {
            this.LastName = lastName;
        }
    
        public string FirstName { get; }
        public string LastName { get; }
        public IEnumerable<Person> Children { get; }
    }
    

    Of course, setting default values to properties by using constructor chaining is a valid design and I've used it myself when I needed it, but that's usually not the case.

    The keyword base

    This keyword always refers to the base (or parent) class. You will see it a lot when overriding methods and properties as well.
    When it comes to constructors - your assumption is correct - it does refer to the base (or parent) class. So when used in a constructor (like in your Circle example), you can control what overload of the base constructors your derived (or child) class constructor will execute.
    So, for instance, if your base class contains three constructors, you can choose which one of them you want to call.

    c# will chain constructors of derived class to the default constructor of the base class unless specified otherwise.
    Please note that if you inherit from a class that has no default (meaning: parameterless) constructor you must specify the : base(...) in your constructors, even if there is only one constructor to your base class (since that's the only way you can pass the needed parameters to it).