views:

376

answers:

4

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

+3  A: 

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:

Juan Manuel
could you elaborate? is it simmilar to the winforms designer file?
andrewWinn
@andrewWinn - yep, it is equivilent of the winforms designer file - in ASP.NET 1.1 there would be all the control declarations at the top of your code-behind, and then a collapsed region at the bottom commented along the lines of "Designer Generated, Do Not Modify" where all the events were wired up.
Zhaph - Ben Duguid
+9  A: 
Pascal Paradis
This is one of those "lets make a chart out of something that shouldn't be a chart" charts.
womp
+1  A: 

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.

JustLoren
Plus it helps keep all of the ugly generated code away from you and accidently editing it. You have to be much more purposeful now to edit it.... :)
klabranche
+1  A: 

The other reason for partial files is to handle the case where some of the class definition is generated by a tool (And may be regenerated at some point) and the rest of the class is implemented by you.

In such cases, not using a partial class would result in either your code being overwritten, or the generation process having difficulty doing its job (If it can do it at all).

With the partial classes in place, the generated code can be easily regenerated without touching your code.

Another good example of this is when using the DataContext classes for LINQ-to-SQL: The really clever stuff is generated into one set of partial class files and you can provide implementations - for validation etc. - in the other partial class, safe in the knowledge that re-generation won't destroy your work.

belugabob