Register now or log in to join your professional community.
When working on large projects, spreading a class over separate files enables multiple programmers to work on it at the same time.
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 it creates Windows Forms, Web service wrapper code, and so on. You can create code that uses these classes without having to modify the file created by Visual Studio.
The partial keyword indicates that other parts of the class, struct, or interface can be defined in the namespace. All the parts must use the partialkeyword. All the parts must be available at compile time to form the final type. All the parts must have the same accessibility, such as public,private, and so on.
If any part is declared abstract, then the whole type is considered abstract. If any part is declared sealed, then the whole type is considered sealed. If any part declares a base type, then the whole type inherits that class.
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.
It is possible to split the definition of a class or a struct, an interface or a method over two or more source files. Each source file contains a section of the type or method definition, and all parts are combined when the application is compiled.