DEV Community

Cover image for C# - Partial Methods for Extensible Code
Keyur Ramoliya
Keyur Ramoliya

Posted on

C# - Partial Methods for Extensible Code

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";
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example:

  • We define a Person class using two partial class definitions. The first part declares a partial void OnNameChanged(string oldName, string newName) method, and the second part implements that method.

  • The Name property setter calls the OnNameChanged 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, the OnNameChanged 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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay