Thursday, 21 June 2012

ASP.net Partial Classes


In ASP.net whenever you right click and add file to the solution/project a new file will be created. In the newly created code behind file you can able to see the Partial keyword just before the class name of that file.

Do you know why the class is mentioned as Partial class in the code behind?  The main reason of having the class file as a Partial class because of the same class name can be used across different physical files this will help the developer to develop the own module without affecting the others code.

The complier will treat different physical files of the partial classes with the same class name as a single entity.

Below code is sample example of a partial class.

1 .file1.aspx.cs

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      //Some Code
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
      //Some Code
      
    }
}

2 .file2.aspx.cs

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      //Some Code
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
      //Some Code
      
    }
}

3 .file3.aspx.cs

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      //Some Code
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
      //Some Code
      
    }
}