#Region directive comes very handy when you have a long code file and you want to categories your code based on some common functionality. It provides collapse and expand feature so you can focus on the code which you need to and rest of the code may be collapsed. #Region directive can be used multiple times in the code. You may only place functions and methods within a #Region.
A #Region directive is followed by a string inside double quotes and ends with #End Region. The code listed in Listing 8 has a few #Region directives separating various related methods. If you do not collapse these regions, code file is longer and if you need to move from top to bottom, you will need lot of scrolling. What if your code is 10 times than this?
#Region "Main Method"
Dim ccc As New ConditionalCompilationClass
Dim exc As New ExternalSourceClass
#Region "Multiple Statements Methods"
Function SingleStatementInMultipleLines(ByVal TableName As String)
Dim sql As String
sql = "SELECT * FROM Titles, Publishers" _
& "WHERE Publishers.PubId = Titles.PubID" _
& "AND Publishers.State = 'NY' " _
& " AND Publisher.State = 'PA' "
Function MultipleStatementInSingleLine(ByVal NumberOne As Integer, _
ByVal NumberTwo As Integer) As Integer
Dim total As Integer = NumberOne + NumberTwo : Dim difference = NumberOne - NumberTwo : Return total
#Region "Comments Methods"
''' This is automated generated standard comment in Visual Studio
''' Use thre singe quotes and hit ENTER, it will generate summary and
''' other comments for the entire function
''' <param name="NumberOne"></param>
''' <param name="NumberTwo"></param>
Function LineContinuationSnippet(ByVal NumberOne As Integer, _
ByVal NumberTwo As Integer) _
' Check if NumberOne > NumberTwo
If (NumberOne > NumberTwo Or _
NumberOne = NumberTwo) Then ' If True, then go here
REM Return NumberOne
REM Return NumberTwo
Return NumberTwo ' REM can be used here too
By implementing #Region directives, we can collapse the regions that are not being used and focus on the only part that we are working on. The collapse regions and cleaner code looks like Figure 2.
Region directives are useful managing code view in Visual Studio 2010. In this article, we saw how we can take advantage of this feature in Visual Studio 2010 to make code readability better in our applications.