Partial Method in C#

How to implement partial method in C#. A partial method can be used as a definition in one part while another part can be the implementation.

A partial class or struct may contain a partial method. Similar to a partial class, a partial method can be used as a definition in one part while another part can be the implementation. If there is no implementation of the partial method then the method and its calls are removed at compile time. Compiler compiles all parts of a partial method to a single method.

A partial method declaration consists of two parts: the definition and the implementation.

The code listing in Listing 1 defines a partial method called InitializeCar in one .cs file and the implementation of the same method in a different .cs file.

  1. public partial class Car  
  2. {  
  3.     // A partial method definiton  
  4.     partial void InitializeCar();   
  5.   
  6.     // Car Exterior Functionality  
  7.     public void BuildTrim() { }  
  8.     public void BuildWheels() { }  
  9. }   
  10.   
  11. public partial class Car  
  12. {  
  13.   
  14.     /// Car Engine  
  15.     public void BuildEngine() { }   
  16.   
  17.     // A partial method implementaion  
  18.     partial void InitializeCar()  
  19.     {  
  20.         string str = "Car";  
  21.         // Put all car initialization here  
  22.     }   
  23.   
  24. }  

Listing 1

Here is the list of the key properties of partial methods. 
  1. A partial method must return void.
  2. A partial method declaration must begin with the keyword partial.
  3. A partial method can have ref but not out parameters.
  4. A partial method is implicitly private, and therefore they cannot be virtual.
  5. A partial method cannot be extern, because the presence of the body determines whether they are defining or implementing.
  6. Partial methods can have static and unsafe modifiers.
  7. Partial methods can be generic. Constraints are put on the defining partial method declaration, and may optionally be repeated on the
Learn more about partial classes and partial methods, continue reading these articles:
 
Next > What are partial classes and Partial Methods in C#