I am new to partial classes and was wondering if someone could give me a "big picture" of why I would use them and what advantage I would gain in the process. Thx.
One great use is separating generated code from hand-written code that belong in the same class.
For example since LINQ to SQL uses partial classes you can write your own implementation of certain pieces of functionality (like Many-to-Many relationships) and those pieces of custom code won't get overwritten when you re-generate the code.
The same goes for WinForms code. All the Designer generated code goes in one file that you generally don't touch. Your hand-written code goes in another file. That way, when you change something in Designer, your changes don't get blown away.
The main use for partial classes is with generated code. If you look at the WPF (Windows Presentation Foundation) network, you define your UI with markup (XML). That markup is compiled into partial classes. You fill in code with partial classes of your own.
The biggest use of partial classes is make life easier on code generators / designers. Partial classes allow the generator to simply emit the code they need to emit and 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 relative to the designer.
If you have a sufficiently large class that doesn't lend itself to effective refactoring, separating it into multiple files helps keep things organized.
For instance, if you have a database for a site containing a discussion forum and a products system, and you don't want to create two different providers classes (NOT the same thing as a proxy class, just to be clear), you can create a single partial class in different files, like
MyProvider.cs - core logic
MyProvider.Forum.cs - methods pertaining specifically to the forum
MyProvider.Product.cs - methods for products
It's just another way to keep things organized.
Also, as others have said, it's about the only way to add methods to a generated class without running the risk of having your additions destroyed the next time the class is regenerated. This comes in handy with template-generated (T4) code, ORMs, etc.
Service references are another example where partial classes are useful to separate generated code from user-created code.
You can "extend" the service classes without having them overwritten when you update the service reference.
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 :)
As an alternative to pre-compiler directives.
If you use pre-compiler directives (namely #IF DEBUG
) then you end up with some gnarly looking code intermingled with your actual Release code.
You can create a seperate partial-class to contain this code, and either wrap the entire partial class in a directive, or omit that code-file from being sent to the compiler (effectively doing the same).
keep everything as clean as possible when working with huge classes, or when working on a team, you can edit without overriding (or always commiting changes)
Partial classes make it possible to add functionality to a suitably-designed program merely by adding source files. For example, a file-import program could be designed so that one could add different types of known files by adding modules that handle them. For example, the main file type converter could include a small class:
Partial Public Class zzFileConverterRegistrar Event Register(ByVal mainConverter as zzFileConverter) Sub registerAll(ByVal mainConverter as zzFileConverter) RaiseEvent Register(mainConverter) End Sub End Class
Each module that wishes to register one or more types of file converter could include something like:
Partial Public Class zzFileConverterRegistrar Private Sub RegisterGif(ByVal mainConverter as zzFileConverter) Handles Me.Register mainConverter.RegisterConverter("GIF", GifConverter.NewFactory)) End Sub End Class
Note that the main file converter class isn't "exposed"--it just exposes a little stub class that add-in modules can hook to. There is a slight risk of naming conflicts, but if each add-in module's "register" routine is named according to the type of file it deals with, they probably shouldn't pose a problem. One could stick a GUID in the name of the registration subroutine if one were worried about such things.
Edit/Addendum To be clear, the purpose of this is to provide a means by which a variety of separate classes can let a main program or class know about them. The only thing the main file converter will do with zzFileConverterRegistrar is create one instance of it and call the registerAll method which will fire the Register event. Any module that wants to hook that event can execute arbitrary code in response to it (that's the whole idea) but there isn't anything a module could do by improperly extending the zzFileConverterRegistrar class other than define a method whose name matches that of something else. It would certainly be possible for one improperly-written extension to break another improperly-written extension, but the solution for that is for anyone who doesn't want his extension broken to simply write it properly.
One could, without using partial classes, have a bit of code somewhere within the main file converter class, which looked like:
RegisterConverter("GIF", GifConvertor.NewFactory) RegisterConverter("BMP", BmpConvertor.NewFactory) RegisterConverter("JPEG", JpegConvertor.NewFactory)
but adding another converter module would require going into that part of the converter code and adding the new converter to the list. Using partial methods, that is no longer necessary--all converters will get included automatically.
Another use is to split the implementation of different interfaces, e.g:
partial class MyClass : IF1, IF2, IF3
{
// main implementation of MyClass
}
partial class MyClass
{
// implementation of IF1
}
partial class MyClass
{
// implementation of IF2
}
Partial classes are primarily introduced to help Code generators, so we (users) don't end up loosing all our work / changes to the generated classes like ASP.NET's .designer.cs class each time we regenerate, almost all new tools that generate code LINQ, EntityFrameworks, ASP.NET use partial classes for generated code, so we can safely add or alter logic of these generated codes taking advantage of Partial classes and methods, but be very carefully before you add stuff to the generated code using Partial classes its easier if we break the build but worst if we introduce runtime errors. For more details check this http://www.4guysfromrolla.com/articles/071509-1.aspx
Another use i saw is,
Extending a big abstract class regarding data access logic ,
i have various files with names Post.cs,Comment.cs,Pages.cs...
in Post.cs
public partial class XMLDAO :BigAbstractClass
{
// CRUD methods of post..
}
in Comment.cs
public partial class XMLDAO :BigAbstractClass
{
// CRUD methods of comment..
}
in Pages.cs
public partial class XMLDAO :BigAbstractClass
{
// CRUD methods of Pages..
}