The Region Directive in VB.NET

It's still available to programmers for organizing code

When VB.NET 1.0 was introduced, one of the biggest changes was that all of Microsoft's generated source code was included and available to you as a programmer in your project. The older Visual Basic versions created indecipherable p-code that you couldn't see and couldn't change. Even though the generated code was in your program, it was a bad idea to change any of it. If you didn't know what you were doing, chances were high you'd break your project by changing Microsoft's generated code.

In VB.NET 1.0, all this generated code was only protected by being enclosed in a Region section of the program, where it was one click away from being viewable and changeable as part of your source code. Beginning with VB.NET 2005 (Framework 2.0), Microsoft put it in an entirely different file using partial classes, but the Region directive is still available, and you can use it to organize your own code.

This simple program shows how Region works:

 Public Class Form1
    Dim myInstance As LongAndIntricateCode
 End Class
 
 Public Class LongAndIntricateCode
    ' Assume you paid a professional
    ' statistician a zillion dollars
    ' to code this custom calculation that
    ' nobody in your company understands.
    ' That's what is in this class!
 End Class 

You could compile this into a DLL to protect it or use the partial class idea that Visual Studio uses or just make a separate class file, but the easiest way to keep it out of the way and still make it part of the same file is to use the Region directive.

That makes the code look like this:

 Public Class Form1
    Dim myInstance As LongAndIntricateCode
 End Class
 
 Don't Touch This! 

Just surround the code you want to disappear with:

 #Region "Don't Touch This!"
 ... 
 #End Region 

For debugging purposes, you can use this as a way to bring parts of your code closer together so you can see them on the same screen:

    ' Code that I'm debugging
 #Region "Make This Disappear"
    ' 5,000 lines of code that is irrelevant
 #End Region
    ' More code that I'm debugging 

You can't use a Region or an End Region inside a function or subroutine. In other words, this example below doesn't work:

 Public Sub ThisSub()
    #Region "Don't Touch This!"
    ' The code for this subroutine
    #End Region
 End Sub 

That's OK. Visual Studio collapses subroutines without a Region directive. You can nest Regions. In other words, this does work:

 #Region "Outer Region"
 Public Class FirstClass
    ' Code for FirstClass
 End Class
 #Region "Inner Region"
 Public Class SecondClass
    'Code for SecondClass
 End Class
 #End Region
 #End Region 

If you borrow code from the internet, look for Regions in it before you add it to your code. Hackers have been known to embed bad stuff inside a Region to keep it from being noticed.