There are several situations when
splitting a class definition is desirable:
- 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.
- To split a class definition, use the partial keyword
modifier, as shown here:
C#
public partial class Calculation
{
public void Sum()
{
}
}
public partial class Calculation
{
public void Multiplication()
{
}
}
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 partial keyword. 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.
All the parts that specify a base
class must agree, but parts that omit a base class still inherit the base type.
Parts can specify different base interfaces, and the final type implements all
the interfaces listed by all the partial declarations. Any class, struct, or
interface members declared in a partial definition are available to all the
other parts. The final type is the combination of all the parts at compile
time.