11.3. Partial Types

Partial types are a simple concept that enable a single type to be split across multiple files. The files are combined at compile time into a single type. As such, Partial types cannot be used to add or modify functionality in existing types. The most common reason to use Partial types is to separate generated code. In the past, elaborate class hierarchies had to be created to add additional functionality to a generated class due to fear of that code being overwritten when the class was regenerated. Using Partial types, the generated code can be partitioned into a separate file, and additional code added to a file where it will not be overwritten by the generator.

Partial types are defined by using the Partial keyword in the type definition. The following example defines a Person class across two files:

'File 1 - fields and constructor
Partial Public Class Person
    Private m_Name As String
    Private m_Age As Integer
    Public Sub New(ByVal name As String, ByVal age As Integer)
        Me.m_Name = name
        Me.m_Age = age
    End Sub
End Class
'File 2 - public properties
Public Class Person
    Public ReadOnly Property Age() As Integer
            Return Me.m_Age
        End Get
    End Property
    Public ReadOnly Property Name() As String
            Return Me.m_Name
        End Get
    End Property
End Class

You will notice that the Partial keyword is used only in one of the files. This is specific to VB.NET, because C# requires all partial classes to use this keyword. The disadvantage there is that the Partial keyword needs ...

Get Professional Visual Studio® 2008 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.