Partial Classes in .net

Ever wondered why the Code behind file of an ASP.net page has.......a partial class ?
 
public
partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
}
 

This is because the class is spread across the Designer file and the code behind file of the ASP.net page. When we drag and drop a control on the designer page of an aspx page, it is directly accessible with its ID on the code behind page without adding any reference of the control on the code behind page
 
for ex : lblName.text or txtName.text
 
This is because of the partial class definition. Which essentially means, the code behind file can access the controls placed on the designer file because of the partial class definition
 
So what is a partial class ?
 
A class definition can be split across two or more source files. Each file contains a part of the definition of the class. This can be done using the partial keyword
 
Class definition in one file : 
 
public patial class Employee
{
 
   string firstname;
 
   string
lastname;
 
   int
age;
 
   string
address;
}

 
Class definition in another file :
 
public partial class Employee
{
    public float getFullName()
    { 
    }
}
 

Partial classes help us improve the readability of the code. In case of large class definitions we can split the class into several files and place the methods and variables of that class in the files where they are used.
Ebook Download
View all
Learn
View all