views:

59

answers:

2

I've just encountered a "bug" with the following code.

foreach(Control control in controls)
{
    if(control is TextBox)
    {
        //Do textbox stuff
    }
    if(control is CheckBox)
    {
        //Do checkbox stuff
    }
    if(control is RadioButton)
    {
        //Do radiobutton stuff
    }
}

The bug was that the "radiobutton stuff" and the "checkbox stuff" were both running for a RadioButton.

When stepping through and looking at MSDN, the bug is now obvious, a RadioButton inherits from CheckBox rather than from WebControl directly, therefore both if statements would return true.

I'm posting this question though as I have been coding in ASP.Net since 1.0 was in Beta and this is a complete shock to me along with everyone else on my team.

Whilst it's true that a RadioButton does have all the functionality of a CheckBox, my "assumption" was that it would have been a completely different control.

This obviously "isn't a real question" and more of a discussion point therefore I'm posting as CW.

A: 

Since RadioButton inherits from CheckBox, you could simply change your if statements to:

if(control is RadioButton) 
{ 
    //Do radiobutton stuff 
} 
else if(control is CheckBox) 
{ 
    //Do checkbox stuff 
} 
matt-dot-net
@matt-dot-net: indeed, the fix is easy, the post was more about realising that RadioButton inherited from CheckBox.
Robin Day
A: 

It was probably easier to do; rather than recode all of the same logic, they simply directly inherit and override the rendering to use the radio button...

Ahh, the beauty of inheritance, but this is exactly where it can be painful :-)

It would be best to use an if .. elseif if you only want to run one condition anyway; rather than running each if condition. Helps with performance.

Brian