Revisit Partial Methods in C#

A partial method allows us to separate method definition and implementation. It does not mean that it would allow us multiple implementations. Only a partial class or struct may contain a partial method. One part of the partial class or struct has only declaration and another part of the same partial class or struct may have implementation for that. We can have both in the same part of the partial class or struct. A user may or may not implement the method. A partial method gets executed only when it has an implementation. If the user has not implemented them, the compiler does not include them in the final code.

Rules for Partial Methods:

  • Partial methods are indicated by the partial modifier.
  • Partial methods must be private.
  • Partial methods must return void.
  • Partial methods must only be declared within partial classes.
  • Partial methods do not always have an implementation.
  • Partial methods can be static and generic.
  • Partial methods can have arguments including ref but not out.
  • We cannot make a delegate to a partial method.

Example:

  1. namespace TestPartialMethods  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.             Student obj = new Student();             
  8.             Console.ReadLine();  
  9.         }  
  10.     }  
  11.     public partial class Student  
  12.     {         
  13.         public  Student ()  
  14.         {  
  15.           Admission() ;  
  16.         }  
  17.   
  18.         // A partial method definiton  
  19.         partial void Admission();  
  20.     }  
  21.     public partial class Student  
  22.     {                
  23.         // A partial method implementation  
  24.         partial void Admission()  
  25.         {  
  26.             Console.WriteLine("Inside implementation");             
  27.         }  
  28.     }  
  29.       
  30. }  
Partial methods are useful to customize the code generated by any tool. The generated code may have some partial methods. Implementation of these methods is decided by the developers. If developer decide not to implement then compiler would removes them in the final code. It can also be helpful to distribute the development task among the team members.

Ebook Download
View all
Learn
View all