Partial Class in C#

Partial class is a concept where a single class can be split into 2 or more files. This feature is useful when a class consists of a large number of members (functions, properties and so on).

In such cases functions can be developed in one file and properties in another.

Advantages:
  1. It avoids programming confusion (in other words better readability).

  2. Multiple programmers can work with the same class using different files.

  3. Even though multiple files are used to develop the class all such files should have a common class name.
Note:
  • When compilation is done all the files will be compiled into a single file.

  • When the CLR executes the program it doesn't differentiate between a normal class or partial class.
Foldername : Console

Filename: partial1.cs

  1. using System;      
  2. partial class A      
  3. {      
  4.    public void Add(int x,int y)      
  5.    {      
  6.       Console.WriteLine("sum is {0}",(x+y));      
  7.    }      
  8. }  
Filename: partial2.cs
  1. using System;          
  2. partial class A          
  3. {          
  4.    public void Substract(int x,int y)          
  5.    {          
  6.       Console.WriteLine("Difference is {0}", (x-y));          
  7.    }          
  8. }    
  9.     
  10. class Demo    
  11. {    
  12.    public static void Main()    
  13.    {    
  14.       A obj=new A();    
  15.       obj.Add(7,3);    
  16.       obj.Substract(15,12);    
  17.    }    
  18. }   
Note

When the program is compiled, the .exe file will be created based on the file name in which the main function exists.
 
 
Figure 1: Folder and File names location
 
The following is the procedure for compiling a partial class:
 
 
 
Note: Microsoft also uses partial classes for every program.

For example, create a window application and you will find the following screens.

Code behind file
 

Designer file
 
 
 
 Thank you.


Recommended Free Ebook
Similar Articles