1. Technology

Partial Classes in VB.NET

What they are and how to use them.


Visual Studio
Pantera and Mateusz/Flikr/CC BY 2.0
Updated July 01, 2014

Partial Classes are a feature of VB.NET that is used almost everywhere, but there's not much written about it. This might be because there are not a lot of obvious "developer" applications for it yet. The primary use is in the way ASP.NET and VB.NET solutions are created in Visual Studio where it's one of those features that is normally "hidden".

A partial class is simply a class definition that is split into more than one physical file. Partial classes don't make a difference to the compiler because all the files that make up a class are simply merged into a single entity for the compiler. Since the classes are just merged together and compiled, you can't mix languages. That is, you can't have one partial class in C# and another in VB. You can't span assemblies with partial classes either. They all have to be in the same assembly.

This is used a lot by Visual Studio itself, especially in web pages where it is a key concept in "code behind" files. We'll see how this works in a Visual Studio, but understanding what changed in Visual Studio 2005 when it was introduced is a good starting point.

In Visual Studio 2003, the "hidden" code for a Windows application was all in a section called a Region marked "Windows Form Designer generated code". But it was still all there in the same file and it was easy to view, and change, the code in the Region. All of the code is available to your application in .NET. But since some of it is code that you should <almost> never mess with, it was kept in that hidden Region. (Regions can still be used for your own code, but Visual Studio doesn't use them anymore.)

In Visual Studio 2005 (Framework 2.0), Microsoft did approximately the same thing, but they hid the code in a different place: a partial class in a separate file. You can see this at the bottom of the illustration below:

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

One of the syntax differences between Visual Basic and C# right now is that C# requires that all partial classes be qualified with the keyword Partial but VB does not. Your main form in VB.NET doesn't have any special qualifiers. But the default class statement for an empty Windows application looks like this using C#:

public partial class Form1 : Form

Microsoft's design choices on things like this are interesting. When Paul Vick, Microsoft's VB designer, wrote about this design choice in his blog Panopticon Central, the debate about it in the comments went on for pages and pages.

Lets see how all this works with real code on the next page.

  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.