ASP.NET - partial class in .net - Asked By aman on 29-Aug-11 03:10 AM

hi all,
 
what is partial class in .net?
how to create a partial class in asp.net?
if possible please give me some example so that i can make it use full .....

thanks
Reena Jain replied to aman on 29-Aug-11 03:14 AM
hi,

hi,

Definition :Partial types are allow to define a single class in multiple files (more than one file), when compilation time theses classes are combined to form a single class.

The partial modifier is not available on delegate or enumeration declarations.
In old days when we write a big class it gets difficult to read the code of whole class. C# solves this problem through partial classes. With the help of partil calsses we can divide single class in multiple pieces and compiler joins them automatically the end. Here is a sample:-

//here is a big class:-
 
  public class BigClass
  {
  public void FunctionA()
  {
  }
  public void FunctionB()
  {
  }
  }
 
//and Through partial classes i have divided it different partial classes:-
 
 public partial class BigClass2
  {
  public string PropertySample { get; set; }
  }
 
  public partial class BigClass2
  {
  public void FunctionA()
  {
    string test = PropertySample;
  }
  }
     public partial class BigClass2
  {
  public void FunctionB()
  {
  }
  }

hope this will help you
Irfan Khan replied to aman on 29-Aug-11 03:48 AM

Partial Classes in ASP.NET

Partial class is a new functionality that is included in Visual Studio .Net 2005 and is supported in ASP.Net 2.0. This new functionality helps you to split a single class into multiple partial classes. These partial classes can be in different individual files.

In the earlier versions of Visual Studio .Net 2005, while you create an ASP.Net application, you might have seen that a single class has to be in a single file. You will be beginning a class and ending that class in the same file. It was not possible to split a single class across multiple files. This new feature, partial class, allows you to allot different developers to develop the code for different functionalities that are available in a single class. These functionalities can be developed in partial classes and then compiled to form the required assembly.

In the previous versions of the Visual Studio .Net IDE, when you create a new ASP.Net webform, the name of the web form is used as a class in the code-behind file. Apart from that, you would have seen lots of code generated by Visual Studio .Net itself. In the latest version of the Visual Studio .Net IDE, the codes that are generated by Visual Studio .Net are in a separate file as a partial class. Hence a user who creates a new webform would see a partial class for that page, when the user uses the code-behind file. This way the code that is seen in the code-behind file is minimal for a particular webform.

The compilers for VB.Net or C# look for the partial classes and integrate them while compiling, to form the intermediate language. This intermediate language is the same when compared to the intermediate language that is generated, if all the partial classes are combined to form a single class in a single file. There is no modification done in the CLR for the implementation of partial classes.

Let us look at a sample code for the implementation of the partial classes. The code would have an interface which is implemented across different classes. When compiled, the compiler would integrate all the partial classes and see whether all the methods of the interface have been implemented. If it is not, then the compiler will throw an error. If all the interfaces are implemented then it will compile to form the intermediate language. The code given below gives the implementation of the partial classes.

'-----File_1.vb
Imports System
Interface IPartialClass
Sub PrintEmployeeName(ByVal sName As String)
Sub PrintEmployeeName()
End Interface

Partial Class MyPartialClass
Private sName As String = "sName Variable - John Peter - From Partial Class."
End Class

'-----File_2.vb
Imports System
Partial Public Class MyPartialClass
Implements IPartialClass

Public Sub PrintEmployeeName(string str)
Response.Write(str)
End Sub
End Class

'-----File_3.vb
Imports System
Partial Public Class MyPartialClass
Public Sub PrintEmployeeName()
Response.Write(sName)
End Sub
End Class


'-----Write the following code in the click event of a button control '-----in the .aspx page
Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim PClass as New MyPartialClass()
PClass.PrintEmployeeName("String from a Partial Class.")
PClass.PrintEmployeeName()
End Sub

There are three class files namely, File_1.vb, File_2.vb, and File_3.vb. The first file has the interface IPartialClass declared and a partial class MyPartialClass which declares a string variable. The second file has the same partial class which implements the interface IPartialClass. This interface has two methods to be implemented. The first method is implemented in the second file and the second method is implemented in the third file. Altogether, all the methods are implemented in some partial class. It is not necessary for the class in the first file File_1.vb to have the Partial keyword. But if you are writing your code for partial classes in C#, it is necessary for all the classes to have the ‘partial’ keyword. This is a significant difference between VB.Net and C# in using partial classes. Note that the method PrintEmployeeName() is implemented in the third file File_3.vb and the method PrintEmployeeName(string str) is implemented in the second file File_2.vb. The string variable sName that is used in the third file is declared in the first file File_1.vb.

Create a new webform in your project and add a button control. In the click event of the button control, write the code which calls both the methods of the interface as given in the above code listing. Upon compilation, the .aspx page will execute properly displaying the appropriate strings. This proves that although the classes are split in different files, the usage of the Partial keyword helps in binding all the partial classes together during compilation and produces a single intermediate language file. The CLR finds no difference in the intermediate language, even if the IL is produced by having a single class in a single class file, where all the methods of the interface are implemented in a single class in a single class file. Since we are dealing with different files for a single class, even if you missed out implementing one method of an interface, the intellisense of Visual Studio .Net 2005 will point it out to you, thus enabling you to implement the missed out method of the interface. This is one among the advantage of using a Visual Studio .Net 2005 IDE for ASP.Net 2.0 applications.

This type of splitting the class file is particularly useful if a single class runs to thousands of lines of code with different functionalities across different methods. Productivity of the project team is increased since a single class file is split across the team members and implemented as partial classes.

Irfan Khan replied to aman on 29-Aug-11 03:51 AM

Introduction


Partial classes and partial methods are two programming language features of .NET programming languages that make it possible for developers to extend and enhance auto-generated code. In a nutshell, http://en.wikipedia.org/wiki/Partial_class allow for a single class's members to be divided among multiple source code files. At compile-time these multiple files get combined into a single class as if the class's members had all been specified in a single file. Partial methods are methods defined in a partial class that are (optionally) divided across two files. With partial methods one file contains the method signature - the method name, its return type, and its input parameters - while the body is (optionally) defined in a separate file. If the partial method's body is not defined then the compiler automatically removes the partial method signature and all calls to the method at compile-time.

Partial classes and partial methods are most commonly used in auto-generated code. The framework or tool that is auto-generating the code can create the auto-generated classes as partial classes. If the developer using the auto-generated code wants to extend the functionality of the class by adding new methods or properties she can do so by creating a new partial class file and putting her additions there. By having these additions in a separate file there's no risk of the tool overwriting the developer's changes when regenerating the code.

Regardless of whether you know the ins and outs of partial classes you use them every time you create an ASP.NET web page using a code-behind class. And if you routinely use auto-generated libraries, like LINQ to SQL or Typed DataSets, then it behooves you to be familiar with both partial classes and partial methods, as they offer opportunities for safely extending the functionality of auto-generated code. Read on to learn more about how these features work and how you can put them to work.

Splitting a Class Across Multiple Files


Partial classes allow a class's members - its methods, properties, and events - to be split across multiple files; they were introduced as language features to C# 2.0 and Visual Basic 8.0, which were the versions of the languages that shipped with the .NET Framework 2.0 in 2005.. Prior to partial classes a class would need to be entirely defined within one file, like so:

public class Employee
{
   public int EmployeeID;
   public string FirstName;
   public string LastName;
   public decimal Salary;
   
   public void ApplyAnnualCostOfLivingRaise()
   {
    Salary *= 1.05M;
   }
   
   ...
}

With partial classes you can divide the members across separate files. A class is identified as being a partial class via the partial keyword (or Partial in VB), as the following code snippet illustrates:

// This portion of the partial class is defined in EmployeeProperties.cs
public partial class Employee
{
   public int EmployeeID;
   public string FirstName;
   public string LastName;
   public decimal Salary;
}


// This portion of the partial class is defined in EmployeeMethods.cs
public partial class Employee
{
   public void ApplyAnnualCostOfLivingRaise()
   {
    Salary *= 1.05M;
   }
   
   ...
}

Uses of Partial Classes


Partial classes have a variety of uses:
  • They can be used to improve the readability of extremely large classes by partitioning related methods into separate files. (Of course, if your project has very large classes with thousands of lines of code you may want to consider refactoring that massive class into several smaller classes.)
  • For shops using source code control with exclusive checkouts dividing a class into separate files can reduce the likelihood of one developer being blocked from working on a class until it is checked in by another developer. And even when using non-exclusive checkouts - which is usually the preferred method - having a class spread across multiple files reduces merges.
  • Partial classes enable the code generator to generate code in one file while the developer who may need to extend the auto-generated logic can do so in a separate file, which eliminates the worry that the code generator might overwrite a developer's customizations.
The last use of partial classes is the most important one of the three and is one ASP.NET developers enjoy every single time we create an ASP.NET page that uses a code-behind class.

How Partial Classes Are Used In An ASP.NET Application


As you know, an ASP.NET page is typically divided into two files:
  • A markup file with a .aspx extension, and
  • A code file, with a .aspx.cs or .aspx.vb extension
The markup file contains static HTML, Web controls, and data-binding syntax. The code file contains page-level event handlers and event handlers for the Web controls defined in the markup page. Moreover, the code file can reference the Web controls defined in the markup file. This begs the question - how does the code file have access to the Web controls defined in the markup file?

If you look at the class definition in the code file you'll note that the class is marked as a partial class. Here's an example:

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

This code defines a partial class named _Default (or whatever the name of the page happens to be). Note that it does not contain any references to the Web controls defined in the markup portion. That is, if we had a Label Web control in the markup file with its ID property set to lblMessage we could write code in the code-behind class like lblMessage.Text = "Hello, World!" Yet there is no definition for the lblMessage Label in the code-behind class.

The Web controls defined in the markup portion are implemented as properties in an auto-generated partial class. If you are using a Web Application Project you can browse to this partial class directly by visiting the WebPageName.designer.cs or WebPageName.designer.vb file; in a Web Site Project this designer partial class file is created behind the scenes. The following code shows an example of such a designer partial class:

public partial class _Default {
   
   /// <summary>
   /// lblMessage control.
   /// </summary>
   /// <remarks>
   /// Auto-generated field.
   /// To modify move field declaration from designer file to code-behind file.
   /// </remarks>
   protected global::System.Web.UI.WebControls.Label lblMessage;
}

The _Default class is split across two files: the auto-generated designer file and your code-behind class file. The code-behind class file can access the Web controls defined in the markup file because they are actually implemented as properties in the class itself, albeit in a separate, auto-generated file.

Life Before Partial Classes
If you developed ASP.NET 1.x applications then you likely remember what life was like before partial classes. Without partial classes, Visual Studio had to embed the Web control property declarations directly in the code-behind class. This resulted in a hidden region within each code-behind class that defined these properties. With partial classes this low-level scaffolding is placed in a separate file, keeping our code-behind class tidier, more readable, and more maintainable.

Partial classes are also useful with tools like Typed DataSets and LINQ to SQL, which auto-generate class files to assist with data access. It's not uncommon that you need to add additional properties or methods. Doing so involves creating a partial class and adding the needed methods or properties in that separate file. For more information on this technique see http://msdn.microsoft.com/en-us/library/ms171896.aspx and http://msdn.microsoft.com/en-us/library/bb882671.aspx.

Defining a Method Across Two Files


Partial methods allow the definition of a method to be located in one file and the body of the method to be optionally defined in another file. They can only be used in partial classes and were introduced as language features in C# 3.0 and Visual Basic 9.0, the versions that shipped with the .NET Framework 3.5 and Visual Studio 2008.

Returning to our Employee example, with partial methods we could define a partial method named

// This portion of the partial class is defined in Employee.cs
public partial class Employee
{
   public int EmployeeID;
   public string FirstName;
   public string LastName;
   public decimal Salary;

   public partial void ApplyAnnualCostOfLivingRaise();

   public void PerformEndOfYearProcesses()
   {
    ApplyAnnualCostOfLivingRaise();

    ...
   }
}


// This portion of the partial class is defined in EmployeeAnnualCostOfLivingRaise.cs
public partial class Employee
{
   public partial void ApplyAnnualCostOfLivingRaise()
   {
    Salary *= 1.05M;
   }

}

Note that in the first file, Employee.cs, the method ApplyAnnualCostOfLivingRaise is defined as a partial method. No body is supplied, yet the method can be called from other methods in the class, as it is from PerformEndOfYearProcesses. Keep in mind that the partial method's body is optional. If the body is not supplied then when the class is compiled all references to the method ApplyAnnualCostOfLivingRaise are removed. If the body is defined, as it is in the EmployeeAnnualCostOfLivingRaise.cs file, then the compiler treats the method as if it had been defined in the same class file.

Partial methods are especially useful in auto-generated code situations. A code generating tool might now that there are certain extension points that some users are going to be interested in customizing. For example, the objects created in LINQ to SQL have partial methods like OnLoaded, OnCreated, OnPropertyNameChanging, and OnPropertyNameChanged. The auto-generated code calls the OnCreated partial method from its constructor. If you want to run custom code when one of these objects is created you can create a partial class and define the body for the OnCreated partial method. (If you do not need to add such customization then all calls to the OnCreated method are removed at compile-time.)

See http://msdn.microsoft.com/en-us/library/bb882671.aspx for an example of using partial methods to add custom logic to the objects LINQ to SQL auto-generates. And http://blogs.msdn.com/bethmassi/ shows a good example of using partial classes and methods to validate the state of an auto-generated object created by LINQ to SQL in her blog entry, http://blogs.msdn.com/bethmassi/archive/2008/02/25/simple-validation-with-linq-to-sql-classes.aspx.

Conclusion


Partial classes and partial methods are language features available in C# and Visual Basic that, among other uses, provide a simple and safe way to add new functionality or extend existing functionality of auto-generated code. In short, partial classes and partial methods allow class and method definitions to be split across multiple files, which allows the code generator tool to make its writes to one file while your customizations can be made to an entirely separate file. The compiler intelligently combines the definitions together into a single class at compile-time.

s:
http://www.4guysfromrolla.com/articles/071509-1.aspx#postadlink



Anoop S replied to aman on 29-Aug-11 06:04 AM

What is a Partial Class (or struct or interface)?

        A partial class is a feature in which you split a class definition into two or more files. All the parts are joined together when the application is compiled.

 

Situations on which it can be used:

        When multiple programmers need to work on a same class then Partial class is an obvious choice.

 

Conditions:

  • All files should use Partial keyword
  • All files should be available at compile time
  • All files should have same scope specifies.

 

On which it cannot be used:

        It can’t be applied on delegate or enumeration.

 

An Example:

        Let us consider an example where we have 3 .cs files one for educational marks, one for sports marks and one for Cumulative marks and average of a student. A single class name Marks is split across these three .cs files respectively.

 

Create a Visual Studio Windows Application Project. Then add 3 .cs files with the following names respectively EducationMarks.cs, SportsMarks.cs, and Cumulative.cs.

 

        The form which uses these classes and displays the results are shown in the following figure:

 

 

   

  

 

The three .cs files used in the example are:

 

  1. EducationMarks.cs
  2. SportsMarks.cs
  3. Cumulative.cs

 

 

 

The Marks class is split into the three .cs files. The three .cs files are given below with explanations.

 

  1. EducationMarks.cs

 

This class has an integer variable eduMarks in it. There is one method to set value to the eduMarks called  setEducationMark and one method to get value from the variable called getEducationMark.

 

using System;

using System.Collections.Generic;

using System.Text;

 

namespace PartialSamp

{

    partial  class Marks

    {

      int eduMarks;

 

      public void setEducationMark(int em)

      {

        eduMarks = em;

      }

 

      public int getEducationMark()

      {

        return eduMarks;

      }

    }

}

 

  1. SportsMarks.cs

 

This class has an integer variable sportMarks in it. There is one method to set value to the sportMarks called setSportsMark and one method to get value from the variable called getSportsMark.

 

 

using System;

using System.Collections.Generic;

using System.Text;

 

namespace PartialSamp

{

  

 

    partial class Marks

    {

      int sportMarks;

 

      public void setSportsMark(int spm)

      {

        sportMarks=spm;

      }

 

      public int getSportsMark()

      {

        return sportMarks;

      }

 

 

    }

 

}

 

  1. Cumulative.cs

 

This class is the one which sums the sports and educational marks to get the total and then finds the average out of it.

 

using System;

using System.Collections.Generic;

using System.Text;

 

namespace PartialSamp

{

   partial  class Marks

    {

     int totMarks;

     float avg;

 

  

     public int getTotMarks()

     {

       totMarks = sportMarks + eduMarks;

       return totMarks;

     }

 

     public float getavgMarks()

     {

       return totMarks/2;

     }

 

 

    }

}

 

 

 

Note: You can even find the intellisense of the methods of prior .cs files in the current files. For example after typing the EducationMarks class, you will get the methods in it being populated in intellisense in the SportsMarks and Cumulative classes.

 

 

Visual Design:

 

        Create 4 text boxes and 4 labels and a button. Name them as shown in the Figure 1. Then type the following code in the button1_click,

 

private void button1_Click(object sender, EventArgs e)

      {

        Marks m = new Marks();

        m.setEducationMark(int.Parse (  txtEM.Text ) );

        m.setSportsMark(int.Parse(txtSM.Text));

       

        txtTM.Text = m.getTotMarks().ToString() ;

        txtAvg.Text = m.getavgMarks().ToString();

      }

 

Riley K replied to aman on 29-Aug-11 10:43 AM

This is most useful when you are using some tool that automatically generates code for a class, and then you want to manually add some members of your own to that class. Using partial classes, you can add your own members into a separate source file without worry that they will be overwritten when the generator rewrites the automatic file.

One example of a place were this happens is the Windows Forms designer in Visual Studio 2005, which generates code for the Form class in the .designer.cs file, and then provides a separate file for your own code. The dataset designer and the web service proxy class generator are two additional examples.

 

Partial classes are also useful when you have a very large class, so you can distribute the code into various separate source files. This also allows various developers to work on different parts of the class under a source code contol system.


 

reference from MSDN



It is possible to split the definition of a http://msdn.microsoft.com/en-us/library/0b0thckt(v=vs.80).aspx or a http://msdn.microsoft.com/en-us/library/ah19swz4(v=vs.80).aspx, or anhttp://msdn.microsoft.com/en-us/library/87d83y5b(v=vs.80).aspx over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled. 

There are several situations when splitting a class definition is desirable:

  • When working on large projects, spreading a class over separate files enables multiple programmers to work on it at the same time.

  • When working with automatically generated source, code can be added to the class without having to recreate the source file. Visual Studio uses this approach when it creates Windows Forms, Web service wrapper code, and so on. You can create code that uses these classes without having to modify the file created by Visual Studio.

  • To split a class definition, use the http://msdn.microsoft.com/en-us/library/wbx7zzdd.aspx keyword modifier, as shown here:

    public partial class Employee
    {
      public void DoWork()
      {
      }
    }
     
    public partial class Employee
    {
      public void GoToLunch()
      {
      }
    }

    refer this link

    http://msdn.microsoft.com/en-us/library/wa80x488(v=vs.80).aspx