Partial methods allow you to split the declaration and implementation of a method across multiple parts of a partial class. This is often used in code generation scenarios or for creating extensible code, where one part of the code can provide a method's declaration, and another part can provide the implementation.
Here's an example:
using System;
public partial class Person
{
// Declaration of the partial method
partial void OnNameChanged(string oldName, string newName);
private string name;
public string Name
{
get => name;
set
{
if (name != value)
{
string oldName = name;
name = value;
// Call the partial method
OnNameChanged(oldName, value);
}
}
}
}
public partial class Person
{
// Implementation of the partial method
partial void OnNameChanged(string oldName, string newName)
{
Console.WriteLine($"Name changed from {oldName} to {newName}");
}
}
public class Program
{
public static void Main()
{
var person = new Person();
person.Name = "Alice";
}
}
In this example:
We define a
Person
class using two partial class definitions. The first part declares apartial void OnNameChanged(string oldName, string newName)
method, and the second part implements that method.The
Name
property setter calls theOnNameChanged
method when the name is changed, but only if the partial method is implemented in another part of the class.When we change the
Name
property, theOnNameChanged
method is called and prints a message.
Partial methods are especially useful when you want to allow external code or code generators to provide specific behavior for a method while still keeping the method call in the main codebase. They are commonly used in frameworks and libraries to enable extensibility without changing existing code.
Top comments (0)