Question

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.

Was it helpful?

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.

OTHER TIPS

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.

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.

Two people editing the same class, and autogenerated designer code are the two immediate features I can see that were solved by partial classes and methods.

Having designer generated code in a separate file is a lot easier to work with compared to 1.1, where you code could often be mangled by Visual Studio (in windows forms).

Visual Studio still makes a mess of syncing the designer file, code behind and design file with ASP.NET.

If you have some kind of absurdly large class that for some reason are unable or not allowed to logically break apart into smaller classes then you can at least physically break them into multiple files in order to work with it more effectively. Essentially, you can view small chunks at a time avoiding scrolling up and down.

This might apply to legacy code that perhaps due to some arcane policy are not allowed to mess with the existing API because of numerous and entrenched dependencies.

Not necessarily the best use of partial classes, but certainly gives you an alternate option to organize code you might not be able to otherwise modify.

maybe its too late but please let me to add my 2 cents too:

*.When working on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously.

*.You can easily write your code (for extended functionality) for a VS.NET generated class. This will allow you to write the code of your own need without messing with the system generated code

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top