A partial method is a unique kind of method that is split into declaration and definition parts within two partial classes. The declaration section defines the method's signature within one partial class, while the implementation details are provided in a separate partial class.
Partial methods are beneficial in scenarios where method declaration and definition are stored in distinct files. In cases where the method's implementation is absent, the compiler eliminates the signature during compilation.
There are some rules and restrictions apply to the partial method.
- The signature of partial method must be same in both partial classes.
- The partial method must return void.
- No access modifiers are allowed.
- Partial methods are implicitly private.
Let's examine a demonstration showcasing the partial method in action. This instance comprises of two partial classes, with one focusing on the declaration segment and the other concentrating on defining the method.
C# Partial Method Example
using System;
namespace CSharpFeatures
{
partial class A
{
// Declaring partial method
partial void ShowMSG(string msg);
}
partial class A
{
// Implimenting partial method
partial void ShowMSG(String msg)
{
Console.WriteLine(msg);
}
public static void Main(string[] args)
{
// Calling partial method.
new A().ShowMSG("Welcome to the C# Tutorial");
}
}
}
Output
Welcome to the C# Tutorial