Arseni Mourzenko
Arseni Mourzenko

Reputation: 52321

How to share code between Pages and Masterpages without multiple inheritance/code duplication?

I've read the questions/answers explaining that there is no multiple inheritance in C#, that we don't even need it, and that it causes too much problems.

Now, I'm working on a project where I don't really understand how can I do things without multiple inheritance, without duplicating code.

Here's the situation. There is a website with a home page and other pages inheriting from a masterpage (the home page does not inherit from). Both the page and the masterpage are performing some stuff: custom login, statistics, loading of users settings for customization, etc. For the moment, the solution is crappy, since the source code for those tasks is just copied twice.

The home page class inherits from Page. The masterpage, on the other hand, inherits from Masterpage. Logically, it would be great to inherit from a common class too, but it's multiple inheritance, so it's impossible.

So what to do instead?

I thought about several ways, but dislike them:

Any idea?

Upvotes: 1

Views: 1930

Answers (4)

eglasius
eglasius

Reputation: 36037

Use:

standalone class which will be called from the page/masterpage class

but instead of stopping there, add a base page and a base master page. Both use the shared class, and keep the specific pages/master pages code from the indirection.

Upvotes: 1

Andrea Parodi
Andrea Parodi

Reputation: 5614

I suggest you to use the first of your option. If you (understandably) don't feel comfortable with increased level of indirection, you could just create new methods on your standalone classe, e.g:

public bool IsDisplayingTips(){
    return CurrentUser.IsDisplayingTips;
}

and the from your pages just call

bool isDisplayingTips = this.SharedObjects.IsDisplayingTips()

Upvotes: 1

VinayC
VinayC

Reputation: 49185

MasterPage is a just control (that get embedded into the actual page) so you can not have the later approach. However, first approach of creating another helper class is quite feasible.

Yet another approach that we typically use is to have

  1. Common base page class - all pages will inherit from the common base page.
  2. Put common functionality in base page class
  3. From master page, the base page can be referred by casting - for example, myBasePage = (BasePage)this.Page;. This way master page may access common functionality from base page class.

Upvotes: 8

Dan Dumitru
Dan Dumitru

Reputation: 5423

I don't find your 2nd option that dislikable.

I presume you mean creating a base class, e.g. MasterPageBase, derived from System.Web.UI.MasterPage, and creating an empty MasterPage for your homepage, that will inherit from this MasterPageBase.

If done right, it shouldn't slow things down...

Upvotes: 1

Related Questions