Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a base class for both Page and UserControl?

Base classes for Page and UserControl:

public class MyWebPage : System.Web.UI.Page { }

public class MyUserControl : System.Web.UI.UserControl { }

Helper that either of them might use:

void SetSessionValue<T>(string key, T value) { Session[key] = value; }

How can I achieve something like the following?

public class WebObject // can't inherit from both Page and UserControl { 
   protected void SetSessionValue<T>(string key, T value) { 
      Session[key] = value; 
   }
}  

public class MyWebPage : WebObject { }

public class MyUserControl : WebObject { }

Update: I got excited for a second hoping I could solve it this way, but alas it doesn't compile.

public class WebObject<T> : T
{
}
public class MyWebPage : WebObject<System.Web.UI.Page>
{
}
like image 224
Aaron Anodide Avatar asked Oct 20 '11 18:10

Aaron Anodide


Video Answer


1 Answers

You can't. Not easily anyway. I'd recommend just creating a base class for pages and user controls, and duplicating the common code in both. Since user controls are contained in pages, you can also delegate methods in the base user control class to the base page class simply by casting the Page property to your own type:

// Code in the MyUserControlBase class
public int SomeCommonMethod() {
    return ((MyBasePageType)this.Page).SomeCommonMethod();
}

You can also make your life miserable by creating an interface implemented by both base classes and using DI to intercept method and property accessor calls, which would then be routed to some kind of common surrogate class that actually provides the implementation. I probably wouldn't go there :)

like image 56
kprobst Avatar answered Nov 15 '22 04:11

kprobst