Code behind and code beside living in harmony

Onion Blog

Syndication

This week at our .NET Campsight event at Microsoft, we have a great group of students with tons of practical experience building systems in .NET today. As a consequence, they bring up many interesting questions as we discuss some of the new features in .NET 2.0.
Yesterday, after presenting the new 'code beside' model during my ASP.NET 2.0 talk, I was a bit surprised that many of the students were not immediately 'smitten' with the new class generation model :) One of the first questions that came up was how to achieve the same inheritance model we have today to share functionality across many pages in an application.
As it turns out, you can still use inheritance in combination with the partial class model, for what strikes me as a pretty compelling combination. The key is to use both the Inherits= attribute as well as the CompileWith= attribute on your @Page directive as shown here:
 
<%@ Page Language="C#" CompileWith="Default.aspx.cs"
ClassName="Default_aspx" Inherits="PS.MyPageBase" %>
 
Your 'code beside' class will now implicitly derive from PS.MyPageBase instead of the default Page class. Here's what the MyPageBase class might look like:
 
using System;
using System.Web;
using System.Web.UI;
namespace PS
{
  public class MyPageBase : Page
  {
    protected override void OnLoad(EventArgs e)
    {
      Response.Write("Hello world!");
      base.OnLoad(e);
    }
  }
}
 
If you place this in your /code directory, it will be compiled as part of the request cycle, and will then be used as the base class for your partial class. More importantly, you could install this class in an assembly in the GAC (or deploy it in the /bin directory) and add a <Pages .../> element in your web.config so that every page in your entire application derived from it instead of Page.
 
Definitely the best of both worlds...

Posted Nov 03 2004, 10:54 AM by fritz-onion
Filed under:

Comments

Disgruntled ASP.NET 2.0 User wrote re: Code behind and code beside living in harmony
on 11-03-2004 9:05 AM
Anyone complain about Default_aspx as the class name by default?
Fritz Onion wrote re: Code behind and code beside living in harmony
on 11-03-2004 9:43 AM
That's just an artifact of VS.NET 2k5, we're all using emacs here this week :)
Service Station wrote The Inaugural .NET Campsight (the day after)
on 11-07-2004 8:02 PM
Service Station wrote The Inaugural .NET Campsight (the day after)
on 11-09-2004 3:28 PM
Onion Blog wrote New code separation model coming in beta 2
on 11-17-2004 10:39 AM

Add a Comment

(required)  
(optional)
(required)  
Remember Me?