Split a Class into Multiple Files

If you've cracked open a .NET 2.0 Windows Forms class, you'll have noticed that all the automatically generated code is missing! To understand where it's gone, you need to learn about a new feature called partial classes, which allow you to split classes into several pieces.

Note

Have your classes grown too large to manage in one file? With the new Partial keyword, you can split a class into separate files.

How do I do that?

Using the new Partial keyword, you can split a single class into as many pieces as you want. You simply define the same class in more than one place. Here's an example that defines a class named SampleClass in two pieces:

Partial Public Class SampleClass
    Public Sub MethodA( )
        Console.WriteLine("Method A called.")
    End Sub
End Class
    
Partial Public Class SampleClass
    Public Sub MethodB( )
        Console.WriteLine("Method B called.")
    End Sub
End Class

In this example, the two declarations are in the same file, one after the other. However, there's no reason that you can't put the two SampleClass pieces in different source code files in the same project. (The only restrictions are that you can't define the two pieces in separate assemblies or in separate namespaces.)

When you build the application containing the previous code, Visual Studio will track down each piece of SampleClass and assemble it into a complete, compiled class with two methods, MethodA( ) and MethodB( ). You can use both methods, as shown here:

Dim Obj As New SampleClass( ) ...

Get Visual Basic 2005: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.