Partial Classes and Methods
Explore how to define and implement partial classes and partial methods in C#. Understand how splitting class definitions across files improves code organization, supports optional method implementations, and aids collaboration in multi-developer projects. Learn the compiler's role in merging partial types and practical use cases for working with generated code and large teams.
We'll cover the following...
C# allows us to split a class definition across multiple files using the partial keyword. This informs the compiler that the type definition spans several source files.
Define partial classes
Let’s look at how we can define the properties of a Person class in one file.
Line 1: We use a file-scoped namespace to reduce indentation.
Line 6: We add the
partialkeyword beforeclass. This indicates the class definition continues elsewhere.Lines 10–14: We define the properties. We initialize the string properties to
string.Emptyto ensure they are not null when the object is created.
Next, we can define the methods for the same Person class in a completely different file.