Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are aspx code-behind files declared as partial classes?

Why is the code behind a partial class for aspx pages?

like image 380
andrewWinn Avatar asked Aug 25 '09 18:08

andrewWinn


3 Answers

I would refer you to this MSDN Page (ASP.NET Page Class Overview).

When the page is compiled, ASP.NET generates a partial class based on the .aspx file; this class is a partial class of the code-behind class file. The generated partial class file contains declarations for the page's controls. This partial class enables your code-behind file to be used as part of a complete class without requiring you to declare the controls explicitly.

See this chart :

alt text http://img30.imageshack.us/img30/7692/msdnchart.gif

This way you have one class that contains your logic and one class that contains designer stuff. At compile time it is generated as a whole.

like image 59
Pascal Paradis Avatar answered Oct 24 '22 03:10

Pascal Paradis


Because there are other parts of the class (Designer stuff) that's hidden from the developer

For example, instead of this

public MyBasePage : System.Web.UI.Page
{
    ...
    protected System.Web.UI.Label lblName;

    protected void Page_Load(object sender, EventArgs e)
    {
    }
    ...
}

ASP.NET creates those declarations in different physical files, leaving this

public partial class MyBasePage : System.Web.UI.Page
{
    ...

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    ...
}

More info:

  • http://davidhayden.com/blog/dave/archive/2005/01/19/783.aspx
like image 37
juan Avatar answered Oct 24 '22 03:10

juan


The Partial declaration lets you write code in other files - just put it in the same namespace and name the class the same, and they'll be treated as if they're in the same file. It's great for adding functionality to generated files. I most frequently use it to add functions / properties to my LinqToSql objects.

like image 1
JustLoren Avatar answered Oct 24 '22 04:10

JustLoren