C# - What are partial classes? and why use them?

I got this question during an interview, and I had to admit that I had rarely used partial classes. We quickly skipped the subject, but I felt that there was something that I had missed out on in the .net framework:


In short: "Partial classes allows us to split up a class definition into several parts (partial classes)". These parts may be in in different source files, or in the same file. Upon build these different parts are combined into one class. Actually this can also be done to interfaces and structs (but I will stick with classes for simplicity).

When the source code is compiled everything is merged. Annotations/Attributes are merged - which means the compiled class and properties will have annotations from all partial sources. The same happens to interfaces, if every partial implements a different interface, the result will be a class which implements them all. Methods defined in the different partials will also be merged.

Simple example of partial classes merged upon compilation
Above is an example of a "Dog" class which is split into several partial classes and combined when compiled.

But why?

There are a few situations where the partial keyword is ideal. I myself have not used it that often - and I do not know any who use it often. But there is one situation where I find partial classes very useful:

When some code/class is auto generated and needs to be extended. In some projects you might have auto generated code, let it be from UI or an object relational mapper (Entity Framework for example). If you do not wish to check in the auto generated code and want to extend it. Then you can use partials to extend it. This can leave auto generated code out of your source control. You might say that you can just extend the class using inheritance, but this will break the build on the buildserver unless you check in the generated code. This will also make it impossible to inherit from a specific class of your own choosing.

Some might argue that it can be easier for multiple developers to work on the same class when using partials. But I have never found this to be an issue. Source control makes it easy to merge and I do not think having a class split up over several files is a great long term solution. As it will scatter your code which will make it harder to understand the functionality/purpose of the class. If the class is getting too big or is split into "sub classes" by the use of partials I believe you should make two or more classes instead. This would also separate the concerns of the class.

If you wish to know more about partials visit msdn.

oh, and don't forget to have your partials in the same namespace!