A regular C# Windows Form looks like this (the non-designer code):
public partial class BaseForm : Form
{
public BaseForm()
{
// v--- very important method, it is what initializes the form
InitializeComponent();
}
public BaseForm(string title)
: this() // chain with the main constructor
{
this.Text = title;
}
}
Now let's create a derivative form:
public partial class EntityForm : BaseForm
{
public EntityForm()
: base()
{
}
public EntityForm(Entity entity)
: base(entity.Name)
{
}
}
This second form stops working properly. When InitializeComponent();
is called, it is done so in the context of BaseForm
(since it is always defined as non-overrideable and private).
At a glance, a solution might be to have InitializeComponent();
in every constructor, however this means that it might be called several times, creating objects unnecessarily (because of constructor chaining).
A solution to this could be to take it as a general not to call base constructors which sort of defeats the purpose of OOP.
What am I doing wrong? Any ideas?