Saturday, November 28, 2009

StackOverflowException overriding Page in custom class

I was overriding the Page in a custom class that defined user control specific things that my app would do while being run. Each user control inherited from this UserControl class that inherited from System.Web.UI.UserControl. The problem was every time I tried to access the property, I would get a StackOverflowException. My code:


public new VolatileMinds.Web.Common.Page Page { get { return this.Page as VolatileMinds.Web.Common.Page; } }


ended up looking like this;


public new VolatileMinds.Web.Common.Page { get { return System.Web.HttpContext.Current.Handler as VolatileMinds.Web.Common.Page; } }



The problem was that it was trying to recursively cast the Page over and over again, causing the StackOverflowException. Using the Current.Handler sovles this issue.

NOTE: I don't really use absolute namespaces when doing this stuff, I thought it would be easier, however, to understand what was happening if I did.