I find that in some cases, there is a lot of code in a constructor, or a class has two or more constructors which have comparable code. In these cases, I often create a private method. In the former case to improve readability, in the latter to prevent duplicate code.
In some of these cases this results in a private method that should ONLY be called from the constructor (for whatever reason). Is there a way to enforce this? I could imagine doing something like this:
using System.Diagnostics;
public class Foo
{
private bool _constructing = true;
private Foo()
{
_constructing = false;
}
public Foo(string someString) : this()
{
// constructor-specific code
Initialize();
}
public Foo(double someDouble) : this()
{
// constructor-specific code
Initialize();
}
private void Initialize()
{
Debug.Assert(!_constructing, "Initialize method should only be called from constructor");
// shared code
}
}
but this feels somewhat clunky. Does anyone have a better suggestion?
Edit: added constructor chaining to example; I meant for this to be in the original example.
Edit: I think I missed a point in my original question - while chaining constructors does provide a solution in some cases, the chained code is always executed prior to the code in the constructor that you're chaining from (which, incidentally, is why the above example doesn't work). There are cases where you want to execute some part of shared code, and then do something else. I'll add another example to reflect this:
using System.Diagnostics;
public class Foo
{
private bool _constructing = true;
public Foo(string someString)
{
// constructor-specific pre-processing code
Initialize();
// constructor-specific post-processing code
_constructing = false;
}
public Foo(double someDouble)
{
// constructor-specific pre-processing code
Initialize();
// constructor-specific post-processing code
_constructing = false;
}
private void Initialize()
{
Debug.Assert(!_constructing, "Initialize method should only be called from constructor");
// shared code
}
}