views:

74

answers:

3

I have two classes that my pages and controls inherit from. These two classes get the same basic set of information, but as it stands the code is implemented twice. Is there a way to inherit from one base class?

public partial class SessionPage : System.Web.UI.Page
{
 protected override void OnInit(EventArgs e)
 {
  // Loads the session information from the database
  // stores in member vars for the page to use
 }
}

public partial class SessionControl : System.Web.UI.UserControl
{
 protected override void OnInit(EventArgs e)
 {
  // Loads the session information from the database
  // stores in member vars for the user control to use
 }
}
A: 

C# does not allow multiple inheritance, and you need to inherit from either Page or UserControl. So, no, there is no way to inherit from the same base class.

You should propably put the loading-and-initialization logic in a class of it's own; then you could instantiate an instance of this class in the OnInit method. This way you would avoid duplicate code.

driis
+1  A: 

Have a look at this stackoverflow post which treats somehow your issue.

Your

// Loads the session information from the database
// stores in member vars for the page to use

could be implemented as an extension method which would allow you to reuse the logic inside both, the page and usercontrol.

Juri
A: 

You can put the logic in a single class and then have the Page and UserControl custom classes extend a common Interface.

You're still going to have to sub-class Page and UserControl like you are, but at least the logic wouldn't be duplicated, only the overloaded methods and calls to the common logic class. That's still an improvement, though, for reasons of code sharing.

Yadyn