The Region Directive in VB.NET

It's Still Available to Programmers for Organizing Code

Programming code abstract screen of software devoloper.
Juhari Muhade / Getty Images

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:

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:

Just surround the code you want to disappear with:

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:

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

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

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.

Format
mla apa chicago
Your Citation
Mabbutt, Dan. "The Region Directive in VB.NET." ThoughtCo, Feb. 16, 2021, thoughtco.com/the-region-directive-in-vbnet-3424253. Mabbutt, Dan. (2021, February 16). The Region Directive in VB.NET. Retrieved from https://www.thoughtco.com/the-region-directive-in-vbnet-3424253 Mabbutt, Dan. "The Region Directive in VB.NET." ThoughtCo. https://www.thoughtco.com/the-region-directive-in-vbnet-3424253 (accessed April 20, 2024).