I’ve got an ASP.NET usercontrol with a panel that I’m using to hide and show the content, that is,
<asp:Panel runat="server" ID=pnlContainer">
<!-- Some fairly uninteresting content -->
</asp:Panel>
I’ve got a visible property as an overrider, that is,
public override bool Visible
{
get { return pnlContainer.Visible; }
set { pnlContainer.Visible = value; }
}
When I set it I get a stack overflow exception BUT when I change the keyword to new, that is,
public new bool Visible
{
get { return pnlContainer.Visible; }
set { pnlContainer.Visible = value; }
}
Everything works fine. Why is this? I think I’ve just got a generally poor understanding of these keywords and it’s showing here.
Also:
If I put no keyword on – Visual Studio gives a warning saying that either the new or the override keyword should be used as I am masking an already existing member on the user control.
In a way, my strange practice of using a panel to control the visible on the user control isn’t the issue here. With help of the contributors it’s clearly mad and shouldn’t be done. But the issue that interested me was that the override and new keywords behaved in such different ways and the reasons for this.
The difference is summarized on the Microsoft page Knowing When to Use Override and New Keywords (C# Programming Guide).
Review the section of code indicated there. It is also listed below:
The same principle is getting applied to your source. The .NET framework treats all controls on the page as a collection of base Control classes.
Control.Visibleis a virtual property.This means: when the ASP.NET framework invokes
Control.Visiblefor all controls, the onlyControl.Visibleproperty that is invoked from your source is the one marked asoverride, which is what people typically think of with standard polymorphism. Otherwise, if you declare your property asnew, when the ASP.NET framework invokesControl.Visible, your property is never called.Thus the override results in a stack overflow exception since you are then calling your
panel.Visible, which is recursively calling itself many times.