Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

When is it appropriate to use C# partial classes?

I was wondering if someone could give me an overview of why I would use them and what advantage I would gain in the process.

2 Answers

The biggest use of partial classes is to make life easier for code generators / designers. Partial classes allow the generator to simply emit the code they need to emit and they do not have to deal with user edits to the file. Users are likewise free to annotate the class with new members by having a second partial class. This provides a very clean framework for separation of concerns.

A better way to look at it is to see how designers functioned before partial classes. The WinForms designer would spit out all of the code inside of a region with strongly worded comments about not modifying the code. It had to insert all sorts of heuristics to find the generated code for later processing. Now it can simply open the designer.cs file and have a high degree of confidence that it contains only code relevant to the designer.
Aside from the other answers...

I've found them helpful as a stepping-stone in refactoring god-classes. If a class has multiple responsibilities (especially if it's a very large code-file) then I find it beneficial to add 1x partial class per-responsibility as a first-pass for organizing and then refactoring the code.

This helps greatly because it can help with making the code much more readable without actually effecting the executing behavior. It also can help identify when a responsibility is easy to refactor out or is tightly tangled with other aspects.

However--to be clear--this is still bad code, at the end of development you still want one responsibility per-class (NOT per partial class). It's just a stepping-stone :)

Login / Signup to Answer the Question.