ASP.NET tips: CustomBase class with Generic Class

All our ASP.NET pages must derive from System.Web.UI.Page class, but we can take the advantage of inheritance and create a Custom Base Class to manage Security, Session, Error Handling and other repetitive custom codes elegantly. We normally go and create a custom base class that derives from System.Web.UI.Page class which looks something like this.



Then we go and inherit our ASP.NET pages from this class. Note: For ASP.NET 2.0 website projects this file needs to be in a separate class library because of its dynamic compilation mechanism. Our ASP.NET page may look like this.



This is good but, we also have the flexibility to use generic classes and enjoy the benefits of generic classes in our ASP.NET pages and do not need to worry about type casting to and from the universal base type Object, moreover the lack of compile time checking in our pages may sometimes lead to some grief, that we can avoid easily.

Lets look at how we can extend our BasePage using Generic Class. Lets create a an ExtendedBasePage.
In the above code we have declared a type parameter T in the angle brackets, which must derive from RealEstateProperty class, and our ExtendedBasePage derives from our previous Basepage. Then we have used T as return type of property “Property”. You may be wondering by now where did RealEstateProperty class came from.


Here you can see Land and Apartment derives from RealEstateProperty class, these are all business objects of my fictitious realestate website and I want to access the “this.Property” object from my pages. Lets now create a ASP.NET page that derives from ExtendedBasePage<T>.


Here in this ASP.NET page that derives from ExtendedBasePage<Land> I have passed the “Land” as the type parameter, now this.Property is type safe, we cannot go and write this.Property = new Apartment(), the compiler will throw an exception straightway “Cannot implicitly convert type ‘Website.Util.Apartment’ to ‘Website.Util.Land'”. Also notice we do not need to type cast this.Property object to Land to be able to access its public properties.

Here we discussed how we can take advantage of Generic Classes in our ASP.NET custom base pages, hope this helps thank you for being with me so far.

Shahed Khan
CEO Simplexhub
Co-Founder PageFlakes
Founder Smart Code Generator