Introduction
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 code listing in below defines a partial method called InitializeCar in one .cs file and the implementation of the same method in a different .cs file.
// First partial class definition for exterior functionality
public partial class Car
{
// Partial method definition
partial void InitializeCar();
// Car Exterior Functionality
public void BuildTrim()
{
// Implement BuildTrim functionality
}
public void BuildWheels()
{
// Implement BuildWheels functionality
}
}
// Second partial class definition for engine functionality and initialization
public partial class Car
{
// Car Engine
public void BuildEngine()
{
// Implement BuildEngine functionality
}
// Partial method implementation
partial void InitializeCar()
{
string str = "Car";
// Put all car initialization here
}
}
Here is the list of the key properties of partial methods.
- A partial method must return void.
- A partial method declaration must begin with the keyword partial.
- A partial method can have ref but not out parameters.
- A partial method is implicitly private, and therefore they cannot be virtual.
- A partial method cannot be extern, because the presence of the body determines whether they are defining or implementing.
- Partial methods can have static and unsafe modifiers.
- Partial methods can be generic. Constraints are put on the defining partial method declaration, and may optionally be repeated.
Learn more about partial classes and partial methods, continue reading these articles.