CHAPTER 5 UNDERSTANDING ENCAPSULATION
Source Code The ConstData project is included under the Chapter 5 subdirectory.
Understanding Partial Types
Last but not least, it is important to understand the role of the C# partial keyword. A production-level
class could very easily consist of hundreds and hundreds of lines of code. As well, given that a typical
class is defined within a single *.cs file, you could end up with a very long file indeed. When you are
creating your classes, it is often the case that much of the code can be basically ignored after it is
accounted for. For example, field data, properties, and constructors tend to remain as-is during
production, while methods tend to be modified quite often.
If you want, you can partition a single class across multiple C# files, to isolate the boilerplate code
from more readily useful members. To illustrate, open up the EmployeeApp project you created
previously in this chapter into Visual Studio, and after you have done so, open the Employee.cs file for
editing. Currently, this single file contains code of all aspects of the class:
class Employee
{
// Field Data
// Constructors
// Methods
}
// Properties
Using partial classes, you could choose to move the constructors and field data into a brand new file
named Employee.Internal.cs (please note, the name of the file is irrelevant; here I just tacked on the
work internal to represent the guts of the class). The first step is to add the partial keyword to the
current class definition and cut the code to be placed into the new file:
// Employee.cs
partial class Employee
{
// Methods
}
// Properties
Next, assuming you have inserted a new class file into your project, you can move the data fields and
constructors to the new file using a simple cut/paste operation. In addition, you must add the partial
keyword to this aspect of the class definition. For example:
// Employee.Internal.cs
partial class Employee
{
// Field data
}
210
// Constructors