Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload "base" constructor or "this" constructor?

I have few types that derive from simplified Base as shown below.

I am not sure whether to use base class's constructor or this constructor when overloading constructors.

ConcreteA overloads constructors purely using base constructors, while
ConcreteB overloads using this for the first two overloads.

What would be a better way of overloading constructors?

public abstract class Base
{
    public string Name { get; set; }
    public int? Age { get; set; }

    protected Base() : this(string.Empty) {}
    protected Base(string name) : this(name, null) {}
    protected Base(string name, int? age)
    {
        Name = name;
        Age = age;
    }
}

public class ConcreteA : Base
{
    public ConcreteA(){}
    public ConcreteA(string name) : base(name) {}
    public ConcreteA(string name, int? age) : base(name, age)
    {
    }
}

public class ConcreteB : Base
{
    public ConcreteB() : this(string.Empty, null){}
    public ConcreteB(string name): this(name, null){}
    public ConcreteB(string name, int? age) : base(name, age)
    {
    }
}

[Edit] It looks like what Ian Quigley has suggested in his answer seemed to make sense. If I were to have a call that initialize validators, ConcreteA(string) will never initialize validators in following case.

public class ConcreteA : Base
{
    public ConcreteA(){}
    public ConcreteA(string name) : base(name) {}
    public ConcreteA(string name, int? age) : base(name, age)
    {
        InitializeValidators();
    }
    private void InitializeValidators() {}
}
like image 439
dance2die Avatar asked Apr 15 '09 12:04

dance2die


3 Answers

This. Because if you ever place code in ConcreteB(string, int?) then you want the string only constructor to call it.

like image 102
Dead account Avatar answered Sep 18 '22 19:09

Dead account


In general, I'd call "this" rather than "base". You'll probably reuse more code that way, if you expand your classes later on.

like image 21
dommer Avatar answered Sep 17 '22 19:09

dommer


It is fine to mix and match; ultimately, when you use a this(...) constructor, it will eventually get to a ctor that calls base(...) first. It makes sense to re-use logic where required.

You could arrange it so that all the constructors called a common (maybe private) this(...) constructor that is the only one that calls down to the base(...) - but that depends on whether a: it is useful to do so, and b: whether there is a single base(...) ctor that would let you.

like image 20
Marc Gravell Avatar answered Sep 20 '22 19:09

Marc Gravell