C# – When is it appropriate to use C# partial classes

Architecturecclass

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.

Best Answer

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.