Search code examples
c#language-designpartial-classes

C# - what are the benefits of "partial" classes?


I'm asking this because I find it quite a dangerous feature to distribute the class definition so that you can't really be sure if you know all about it. Even if I find three partial definitions, how do I know that there's not a fourth somewhere?

I'm new to C# but have spent 10 years with C++, maybe that's why I'm shaken up?

Anyway, the "partial" concept must have some great benefit, which I'm obviously missing. I would love to learn more about the philosophy behind it.

EDIT: Sorry, missed this duplicate when searching for existing posts.


Solution

  • Partial classes are handy when using code generation. If you want to modify a generated class (rather than inheriting from it) then you run the risk of losing your changes when the code is regenerated. If you are able to define your extra methods etc in a separate file, the generated parts of the class can be re-created without nuking your hand-crafted code.