I’ll be the first person to tell someone that my code design could use improvement. I can’t help but feel that when I have typecasts in my code that its a sign that something needs to be redesigned to remove the typecasts. This question sort of has two parts to it, the first being simply the one posted: Are typecasts a sign of poorly designed code?
The second question is based on the first, if typecasts are as evil as I feel they are, then how could the below situation be avoided?
class InputPanel : Control
{
public event EventHandler InputEvent;
}
class OutputPanel : Control
{
}
class MainWindow : Form
{
public MainWindow()
{
var loadButton = new Button();
loadButton.Click += new EventHandler(HandleButtonClick);
var inputPanel = new InputPanel();
inputPanel.InputEvent += new EventHandler(HandleInputEvent);
bodyControl = inputPanel;
}
private void HandleButtonClick(object sender, EventArgs args)
{
OpenFileDialog dialog = new OpenFileDialog();
if (dialog.ShowDialog(this) == DialogResult.OK)
{
var data = LoadDataFromFile(dialog.FileName);
var inputPanel = bodyControl as InputPanel; // Ugly typecast...
if (inputPanel != null)
{
inputPanel.PopulateFromData(data);
}
}
}
private void HandleInputEvent(object sender, EventArgs args)
{
var outputPanel = new OutputPanel();
bodyControl = outputPanel;
}
Control BodyControl;
}
The reasoning behind the above code is that the MainWindow form contains a MenuStrip (simplified to a button in this example) and a single control (the BodyControl). As the displayed control needs to be changed from the input panel to the output panel, via the button click, you can simply reassign the BodyControl field (adjust parents and such). This means only one panel is loaded at a time, layout logic becomes simplified because there is only one panel to position within the MainWindow (two if you include the MenuStrip) as opposed to conditionally laying out multiply ‘body’ controls based on which state the program is in (input vs. output).
You can make your code much cleaner (and avoid the typecast) by using an interface or a common base class for the two controls (
inputPanelandoutputPanel). Simply storeBodyControlas the base class or interface (instead ofControl). Assuming the interface or base class implements thePopulateFromDatamethod, you wouldn’t need the cast at all.Also be sure you’re aware of the where clause in C#. It can come in handy when dealing with similar scenarios.