Partial Method in C#


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.

  • Definition
  • Implementaion

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.

  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.

Learn more about partial classes and partial methods, continue reading these articles.

Similar Articles
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.