Common base class for user controls and pages in ASP.NET

Now I have a base class for my pages that inherits System.Web.UI.Page and another base class for my usercontrols that inherits System.Web.UI.UserControl , these classes contain the same methods. Since C # does not support multiple inheritance, I cannot combine two classes into one that inherits both pages and UserControl.

What would be the best way to maintain functionality in two base classes, but implement them in one place?

I am going to create an interface and give the two base classes a third class call that contains the implementation of the interface. Is there a better way so that when adding a new method I do not need to do this in three places (although the implementation is only in the third class).

+6
source share
3 answers

If you are using C # 3.0, you can provide your helper methods as extension methods for the System.Web.UI.Control class, from which the System.Web.UI.Page and System.Web.UI.UserControl classes are derived.

 public static class ControlExtensions { public static void DoSomething(this Control obj) { // do something } } 

In Page or UserControl :

 this.DoSomething(); 
+9
source share

I have exactly the same problem. Here is my solution.

I defined an empty interface

 public interface ISecurableWebObject { } 

Then I defined a class that has extension methods for the interface above

 public static class ISecurableWebObjectExtender { public static bool ExtensionMetotX(this ISecurableWebObject obj) { return ...; } } 

I inherited ISecurableWebObject in the page classes and WebUserControl, so the definition of dublicate passed.

  public partial class UcExample : System.Web.UI.UserControl, ISecurableWebObject { protected void Page_Load(object sender, EventArgs e) { if(this.ExtensionMetotX() == true) { ... } } } 
+3
source share

Hmm ... that sounds like using famous helper classes, mostly classes like

 public static class StringHelper { public static string Replace(...) { ... } } 

and calling them like

 string x = StringHelper.Replace(...); 

Although I am often very worried that there are too many of these helpers, because they really somehow remember procedural programming with static methods in them. On the other hand, functions like you describe it (in some base classes that extend the UserControl and the page) usually have this type.

What I often do is to have a StringHelper and corresponding StringExtender, the logical inside of which calls the static methods of the Helper class. This way you can use the functionality with the new C # extension methods or directly through the static class, as usual.

+1
source share

All Articles