Consider the code in the following example:
abstract class Car
{
public abstract Engine CarEngine { get; protected set; }
public Car()
{
CarEngine.EngineOverheating += new EventHandler(CarEngine_EngineOverheating);
}
void CarEngine_EngineOverheating(object sender, EventArgs e)
{
// Subscribing to the event of all engines
}
}
sealed class Toyota : Car
{
public Toyota()
{
this.CarEngine = new ToyotaEngine();
}
public override Engine CarEngine { get; protected set; }
}
abstract class Engine
{
public event EventHandler EngineOverheating;
}
class ToyotaEngine : Engine
{
}
This code, as expected doesn't work since CarEngine has not yet been initialized. What are my options to resolve such a case?
Several options that I see with their cons:
- Subscribe in each child class manually - Results with a lot of boiler plate code and as a result, error-prone.
- Initialize() function - Error-prone and redundant.
I'd be happy to see more ideas.
Thanks!