Partial methods were introduced for the same reasons as .Net 2 partial classes.
A partial class is one that can be divided into several files - the compiler builds them all into one file as it runs.
The advantage of this is that Visual Studio can provide a graphical constructor for part of the class, while encoders work on another.
The most common example is a form constructor. Developers most often do not want to position buttons, input fields, etc. Manually.
- In .Net 1, it was generated by the generated code in the
#region block - In .Net 2 they became separate classes of designers - the form is still one class, it just breaks into one file edited by the developers, and one form developer
This simplifies maintenance. Merging is simpler and less risky of the appearance of a VS-form constructor that accidentally violates manual changes to encoders.
In .Net 3.5 Linq introduced. Linq has a DBML constructor to create your data structures and generates autocode.
The extra bit here is the code needed to provide methods that developers might want to populate.
Since developers will extend these classes (with additional partial files), they cannot use abstract methods here.
Another problem is that most of the time these methods are not called, and calling empty methods is a waste of time.
Empty methods are not optimized .
So Linq generates empty partial methods. Unless you create your own partial to complete them, the C # compiler simply optimizes them.
So that these partial methods always return void.
If you create a new Linq DBML file, it will automatically generate a partial class, something like
[System.Data.Linq.Mapping.DatabaseAttribute(Name="MyDB")] public partial class MyDataContext : System.Data.Linq.DataContext { ... partial void OnCreated(); partial void InsertMyTable(MyTable instance); partial void UpdateMyTable(MyTable instance); partial void DeleteMyTable(MyTable instance); ...
Then in your own partial file you can expand this:
public partial class MyDataContext { partial void OnCreated() {
If you do not extend these methods, they will be optimized correctly.
Partial methods cannot be publicly available - since then they must be there for other classes to call. If you write your own code generators, I see that they are useful, but otherwise they are really only useful for the VS constructor.
The example mentioned above is one of the possibilities:
//this code will get optimised out if no body is implemented partial void DoSomethingIfCompFlag();
Another potential use is if you had a large and complex class spilled over multiple files, you may need partial links in the calling file. However, I think that in this case you should first consider class simplification.