Opentopia Directory Encyclopedia Tools

Partial classes

Encyclopedia : P : PA : PAR : Partial classes


Partial classes, or Partial Types, in object oriented computer programming languages, means the ability to split a class' definition across several files, or several places within a single file. The family of Microsoft .NET languages (C#, VB.NET, etc.), as of their current incarnation (.NET 2.0) have come to support them.

Purpose

The purpose of partial classes is to allow a class' definition to span across multiple files. It is especially useful for: Using partial classes, the code generator processes a separate file, and is thus alleviated from all the above mentioned problems.

Implementation

The implementation of partial classes is quite straight-forward and architecture-transparent. When compiling, the compiler performs a phase of precompilation: first it "unifies" all the parts of the partial class into one logical class, and from that point, normal compilation takes off.

Examples

This simple example, written in Visual Basic .NET, shows how the same class is defined in 2 different files:

file1.vb:

Partial Class MyClass
Private _name As String
End Class
file2.vb:
Partial Class MyClass
Public Readonly Property Name() As String
Get
Return _name
End Get
End Property
End Class
When compiled, the result is the same as the following code:

Class MyClass
Private _name As String
Public Readonly Property Name() As String
Get
Return _name
End Get
End Property
End Class

Partial classes also support the separation of concerns, the following Bear class has different aspects implemented in different parts:

Bear_Hunting.cs

public partial class Bear

}

Bear_Eating.cs

public partial class Bear

}

Bear_Hunger.cs

public partial class Bear

}

For example, if we want to compile a version without support for hunger management (it could be a feature that costs extra), we simply remove the partial declaration in Bear_Hunger.cs.

Now if your program also supported hunger management in other classes you might want to put all those partial class definitions into a separate 'Hunger' directory. You'd then be doing what is usually called Multidimensional separation of concerns, and that would help you update the code and add new features, even if it was the first time you started working with this code.

External links

 


From Wikipedia, the Free Encyclopedia. Original article here. Support Wikipedia by contributing or donating.
All text is available under the terms of the GNU Free Documentation License See Wikipedia Copyrights for details.

Search Titles
0123456789
ABCDEFGHIJ
KLMNOPQRST
UVWXYZ?

E-mail this article to:

Personal Message: