Search code examples
c#constructorradix

Two constructor calls inside one constructor in C#


I know how to call another constructor for a constructor from the same class or the base class, but how can I do both at once? Here is an example of what I am looking to achieve, noting that in a real case we might want to do something more complex than just set a property:

public class BaseClass
{
    public BaseClass(object param)
    {
        // base constructor
    }
}

public class DerivedClass
{
    DateTime Date { get; private set; }

    public DerivedClass()
    {
        Date = GenerateDate();
    }
    public DerivedClass(object param) : base(param)
    {
        // How do I make it call DerivedClass() ?
    }
}

Solution

  • This code actually compiles in Sharp Lab. Not that I had to fix a few secondary things.

    using System;
    
    public class BaseClass
    {
        public BaseClass(object param)
        {
            // base constructor
        }
    }
    
    public class DerivedClass : BaseClass
    {
        public DateTime Date { get; private set; }
    
        public DerivedClass() : this(new object()) { }
    
        public DerivedClass(object param) : base(param)
        {
            //Do Date = GenerateDate(); here
            //Had to cut your pseudo code, as it broke compilation
        }
    }
    

    You had it the wrong way around: You need DerivedClass() to call DerivedClass(object param). With multiple Constructors, the one you actually code out is always the one with the most arguments. All other Constructors are just there to chain towards it, giving a default value each step.