Although it is good programming practice to maintain all source code for a type in a single file, sometimes a type becomes large enough that this is an impractical constraint. Furthermore, programmers often use source code generators to produce the initial structure of an application and then modify the resulting code. Unfortunately, when source code is emitted again sometime in the future, existing modifications are overwritten.
Partial types allow classes, structs, and interfaces to be broken into multiple pieces stored in different source files for easier development and maintenance. Additionally, partial types allow separation of machine-generated and user-written parts of types so that it is easier to augment code generated by a tool.
A new type modifier, partial, is used when defining a type in multiple parts. The following is an example of a partial class that is implemented in two parts. The two parts may be in different source files, for example, because the first part is machine generated by a database mapping tool and the second part is manually authored.
public partial class Customer { private int id; private string name; private string address; private List<Order> orders; public Customer() { ... } } public partial class Customer { public void SubmitOrder(Order order) { orders.Add(order); } public bool HasOutstandingOrders() { return orders.Count > 0; } }
When the previous two parts are compiled together, the resulting code is the same as if the class had been written as a single unit.
public class Customer { private int id; private string name; private string address; private List<Order> orders; public Customer() { ... } public void SubmitOrder(Order order) { orders.Add(order); } public bool HasOutstandingOrders() { return orders.Count > 0; } }
All parts of a partial type must be compiled together such that the parts can be merged at compile time. Partial types specifically do not allow already compiled types to be extended.