If I have a class like this:
public class Foo
{
public IEnumerable<Bar> Bars { get; set; }
public Foo()
{
Bars = new List<Bar>();
}
}
At some stage I re-factor the class and add a secondary constructor which implements the first one like this:
public class Foo
{
public IEnumerable<Bar> Bars { get; set; }
// some more properties were added
public Foo()
{
Bars = new List<Bar>();
}
public Foo(string parameter): this()
{
.... some code here
}
}
I could have also written it similar to this:
public class Foo
{
public IEnumerable<Bar> Bars { get; set; }
// some more properties were added too
public Foo()
{
InitilizeFoo();
}
public Foo(string parameter)
{
InitilizeFoo();
.... some code here
}
private void InitializeFoo()
{
Bars = new List<Bar>();
}
}
Seeing both approaches work in this scenario, is there a benefit or drawback in using one over the other?
Is inheriting constrcutors more efficient and making that code execute faster or is there a drawback which I don’t know about making the second implementation more efficient instead?
One of the key benefits in having one constructor call another constructor is that you can set read-only fields that way, you can’t do that by calling a non-constructor method.
For example:
Performance wise, it’s probably no more or less efficient to call another constructor than to call another method, but it is more readable, in my opinion, for a constructor to call another constructor than to call a separate, private method whose only point is to be called by a constructor.
There could, of course, be situations when having a separate method makes sense, and it’s certainly not “wrong” per se. Chaining constructors just reads better to many for most uses, and there is no negative performance impact.
UPDATE: I performed 10,000,000 iterations of each way (chained vs private initialization method) and the results were so close they were nearly indistinguishable:
So really, performance-wise there is nearly no benefit either way. The main benefit is with chained constructors you can set
readonlyfields, and in most cases it is more readable.