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() {}
}
This. Because if you ever place code in ConcreteB(string, int?) then you want the string only constructor to call it.
In general, I'd call "this" rather than "base". You'll probably reuse more code that way, if you expand your classes later on.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With