Sunday, October 20, 2019

Using the Region Directive in VB.NET

Using the Region Directive in VB.NET When VB.NET 1.0 was introduced, one of the biggest changes was that all of Microsofts 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 couldnt see and couldnt change. Even though the generated code was in your program, it was a bad idea to change any of it. If you didnt know what you were doing, chances were high youd break your project by changing Microsofts 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 cant use a Region or an End Region inside a function or subroutine. In other words, this example  below doesnt  work: Thats 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.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.