#636 – The Reason for Partial Methods

Partial methods allow one portion of a class to declare one or more methods and then another portion of the class, in a different file, to optionally implement one or more of those methods.

You’ll typically see partial methods used when some tool generates a portion of a class and the user (developer) is expected to develop the remainder of the class.  The class in question is a partial class, because it is split across two (or more) files–the tool-generated part and the user-generated part.

Using partial methods, the tool-generated code can declare a number of optional methods that are basically extensibility points for the user-generated code.  The tool-generated will call these methods, but only if the user decides to implement them.  If the user does not implement them, they are simply not called.

#633 – The Implementation of A Partial Method Is Optional

A partial method is a method declared in one portion of a partial class and implemented in another.

    // Dog-1.cs
    public partial class Dog
        public string Name { get; set; }

        // Partial method declaration--no implementation here
        partial void Growl();

One interesting thing about partial methods is that implementing them is optional.  In other words, you may provide an implementation of the Growl method shown above, in a separate file containing additional implementation for the partial class Dog.  But the compiler won’t complain if you never provide an implementation for the Growl method.


#631 – Code-Generation Tools and Partial Classes

C# supports the idea of partial classes–splitting the implementation of a class across multiple files.

You might use partial classes for code that you author, to help organize your code.  (E.g. Creating a separate file for each interface that your class implements).  But the main reason that partial classes are useful is that code generation tools can implement their portion of a particular class in their own file.  Because a code generator “owns” the file, it can destroy and re-build its part of your class without affecting the code that you’ve written.