c# 4.0 - best way to refactor a block of "If (something is Type) {}" statements?
- by Andrew Johns
I've got some code that looks like this,
public void ResetControls(Control controlOnPage)
{
if (controlOnPage is TextBox)
{
ResetTextBoxControl(controlOnPage);
}
if (controlOnPage is MediaPicker)
{
((MediaPicker)controlOnPage).Media = null;
}
if (controlOnPage is RelatedContentPicker)
{
((RelatedContentPicker)controlOnPage).RelatedContentCollection = null;
}
...
...
foreach (Control child in controlOnPage.Controls)
{
ResetControls(child);
}
}
The idea behind it is that I can pass a page to the method and it'll recursively reset all the controls on it to their default states - in the case of MediaPicker and RelatedContentPicker, these are user controls that I've created.
FXCop warns me "Do Not Cast Unnecessarily" for this code - but I'm unsure how to rewrite it to make it better. Any ideas?