1. Technology

Partial Classes in VB.NET

Adding a Partial Class to a VB Project


On the previous page, the concept of partial classes was explained. We convert a single class into two partial classes on this page.

Here's an example class with one method and one property in a VB.NET project

 Public Class CombinedClass
    Private m_Property1 As String
    Public Sub New(ByVal Value As String)
       m_Property1 = Value
    End Sub
    Public Sub Method1()
    End Sub
    Property Property1() As String
          Return m_Property1
       End Get
       Set(ByVal value As String)
          m_Property1 = value
       End Set
    End Property
 End Class 

This class can be called (for example, in the Click event code for a Button object) with the code:

 Dim ClassInstance As New _
    CombinedClass("About Visual Basic Partial Classes")

We can separate the properties and methods of the class into different physical files by adding two new class files to the project. Name the first physical file Partial.methods.vb and name the second one Partial.properties.vb. The physical file names have to be different but the partial class names will be the same so Visual Basic can merge them when the code is compiled.

It's not a syntax requirement, but most programmers are following the example in Visual Studio of using "dotted" names for these classes. For example, Visual Studio uses the default name Form1.Designer.vb for the partial class for a Windows form. Remember to add the Partial keyword for each class and change the internal class name (not the file name) to the same name. I used the internal class name: PartialClass.

The illustration below shows all of the code for the example and the code in action.

Click Here to display the illustration
Click the Back button on your browser to return

Visual Studio "hides" partial classes such as Form1.Designer.vb. On the next page, we learn how to do that with the partial classes we just created.

  1. About.com
  2. Technology
  3. Visual Basic
  4. Using VB.NET
  5. Partial Classes in Visual Basic .NET

©2014 About.com. All rights reserved.