29 October 2013

Partial Classes in C#

Introduction
A Partial class is one that can be split among multiple physical files. This feature was introduced with the release of C# version 2.0. With C#, we can split the source code for a class into separate files so that we can organize the definition of a large class into smaller, easier to manage pieces. When we split a class across multiple files, we define the parts of the class by using the partial keyword in each file. Each file contains a section of the class definition, and all parts are combined when the application is compiled. Look at the example below:

Original and Single Class File (Calculation.cs)

class ClassRoom
{
   
 private int boycount;   //field
    public ClassRoom()     //default constructor
   
 {
       
 boycount = 30;
   
 }
    public ClassRoom(int bcount)     //overloaded constructor
   
 {
       
 boycount = bcount;
   
 }
    public double Avg()     //method
   
 {
       
 //statements goes here
   
 }
}

Splitted Class Files into two parts


//Calculation1.cs
partial class ClassRoom
{
   
 private int boycount;   //field

   
 public ClassRoom()     //default constructor
   
 {
       
 boycount = 30;
   
 }
}
//Calculation2.cs
partial class ClassRoom
{
   
 public ClassRoom(int bcount)     //overloaded constructor
   
 {
       
 boycount = bcount;
   
 }
    public double Avg()     //method
   
 {
       
 //statements goes here
   
 }
}
Now, when we compile a class that has been split into separate files, we must provide all the files to the compiler.
Partial Classes Rules and Advantages
To work on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously.
When working with automatically generated source, code can be added to the class without having to recreate the source file.
To split a class definition, use the partial keyword modifier.
All the parts must have the same accessibility, such as public, private, and so on.
The partial modifier can only appear immediately before the keywords class, struct, or interface.
Benefit of partial classes:

1) More than one developer can simultaneously write the code for the class.

2) You can easily write your code (for extended functionality) for a VS.NET generated class. This will allow you to write the code of your own need without messing with the system generated code.


No comments:

Post a Comment