I want to be able to call a particular method automatically upon construction of a derived object, however I can\'t think how to do it. The following code illustrates. Another a
Unfortunately there's no built-in way to do what you want (it's a fairly-often-requested feature).
One workaround is to implement a factory pattern, where you don't create objects by calling the constructor directly, but instead implement a static method to create them for you. For example:
public class MyClass
{
public MyClass()
{
// Don't call virtual methods here!
}
public virtual void Initialize()
{
// Do stuff -- but may be overridden by derived classes!
}
}
then add:
public static MyClass Create()
{
var result = new MyClass();
// Safe to call a virtual method here
result.Initialize();
// Now you can do any other post-constructor stuff
return result;
}
and instead of doing
var test = new MyClass();
you can do
var test = MyClass.Create();