What is a difference between partial class and partial method and what are they good for?

Experience Level: Senior
Tags: .NET C#

Answer

Partial class

Marking class as partial you can split its definition to multiple files. It is useful in cases where some part of the class is automatically generated by some automation tool/code generator/designer.

If your class is big and you think you could make it smaller by using partial, stop and think first. Doesn't your class do to much? Aren't you breaking single responsibility principle (SRP)? If so, refactor it. Using partial in such cases is a nasty code smell.

Partial method

Partial methods were introduced to extend existing classes that you have no control over (part of the framework or auto-generated code).

Related C# job interview questions