Since VS2005 created the ability to use partial classes, the feature has been available to developers across the .NET community. This post is to provide a quick description of using inheritance and an example I found it to be particularly useful.
According to Microsoft, partial classes are most useful in these scenarios:
- When working on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously.
- When working with automatically generated source, code can be added to the class without having to recreate the source file. Visual Studio uses this approach when creating Windows Forms, Web Service wrapper code, and so on. You can create code that uses these classes without having to edit the file created by Visual Studio.
So by excluding bullet point #1 because I don’t agree with it (any source control system, even VSS, should facilitate this), we’re pretty much left with code generation. The main reason partial classes were created is in order to allow part of a class to be regenerated via CodeGen and not have that blow away other code you have added since generation.
I recently found this helpful in working with an industry standard XML definition called WITSML. We wanted to have C# data objects defined by the XML schema provided by the standard. However, we also wanted to have these objects decorated with certain features that allowed the objects to fit into our overall data integration architecture. In order to accomplish this, we simple created a matching partial class definition where we inherited from our base class and added any additional functions we wanted to have in the item. I would provide some code samples, but this walks the line on some intellectual property issues since the concept belongs to my employer, so I’ll leave it up to your imagination
An interesting facet of the inheritance capability and the differences between C# and VB is discussed by Cory Smith on his blog.