views:

141

answers:

2

When you create a webpage in ASP.net, the codebase inherits System.Web.UI.Page

Now when I extend the page object to check for SessionExpired for example, I create a new class and inherit from system.web.ui.page, and overwrite some functions.

The problem then is that on each page, I have to replace system.web.ui.page with my custompage class.

Is there a way to extend a class by adding methods or modifying its methods directly (e.g. add the sessionExpired check to System.Web.UI.Page) ?

I'm using .NET 2.0

+2  A: 

You can add extension method for System.Web.UI.Page class that will check session expiry for you. I think something like this will work.

public static bool CheckSessionExpired(this System.Web.UI.Page page)
{
   ///...check session expiry here...///
}

Extension method is feature of C# 3.0, so you will have to install C# 3.0 compiler to compile the code (VS.NET 2008 or higher)

As you are using .NET 2.0, you will have to create an attribute because extension method have dependency on an attribute that is only part of .NET 3.5 (System.Core.dll). Just create the following attribute in your project and you will be able to use extension methods:

using System;

namespace System.Runtime.CompilerServices
{
    public class ExtensionAttribute : Attribute { }
}
cornerback84
+1  A: 

VB 2008 supports Extension Methods, but: Extension Methods can't override base class methods, only add new methods. They don't have direct access to the members of the extended type. Extending is not Inheriting. Therefore, you can add the sessionExpired check via extension methods and invoke it whenever you need, but you can't use it to add any triggering mechanism to System.Web.UI.Page's behaviour.

M.A. Hanin
If that is true, which it probably is, then there's no point in extension methods - I can just as well declare a method somewhere else and use that, or inherit from a base class and add a method. Makes little difference.
Quandary
Yeah, well, Extension Methods are meant to be used in other scenarios, and they aren't too powerful as they are. They make things more convenient, but they don't give you much leverage.
M.A. Hanin