Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 767
sharkin Avatar asked Sep 18 '09 09:09

sharkin


3 Answers

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.

like image 103
Matt Hamilton Avatar answered Oct 22 '22 05:10

Matt Hamilton


The great benefit is to hide computer generated code (by the designer).
Eric Lippert has a recent blog post about the partial-keyword in general.

Another usage could be to give nested classes their own file.

like image 33
tanascius Avatar answered Oct 22 '22 07:10

tanascius


An other point is, that when a class implements multiple interfaces, you can split the interface implementations on diffrent files.

So every code file has only the code that belongs to the interface implementation. It´s according to separation of concerns concept.

like image 30
Jehof Avatar answered Oct 22 '22 07:10

Jehof