Chapter 6. Visual Basic Code Editor

The Visual Studio IDE includes editors for many different kinds of documents, including several different kinds of code. For example, it has Hypertext Markup Language (HTML), Extensible Markup Language (XML), Extensible Application Markup Language (XAML), and Visual Basic editors. These editors share some common features, such as displaying comments and keywords in different colors.

As a Visual Basic developer, you will use the Visual Basic code editor frequently, so you should spend a few minutes learning about its specialized features. The most obvious feature of the code editor is that it lets you type code into a module, but the code editor is far more than a simple text editor such as Notepad. It provides many features to make writing correct Visual Basic code easier.

This chapter describes some of the most important of these features. Many of these tools are invaluable for understanding and navigating through the code so, even if you have worked with Visual Studio before, you should take some time to read through this chapter and experiment with the tools it describes.

Figure 6-1 shows the code editor displaying some Visual Basic code at runtime. To make referring to the code lines easier, this figure displays line numbers. To display line numbers, invoke the Tools menu's Options command, navigate to the Text Editor

FANTASTIC FEATURES
The Visual Basic code editor provides many features, including line numbers and icons that indicate breakpoints and bookmarks.

Figure 6.1. The Visual Basic code editor provides many features, including line numbers and icons that indicate breakpoints and bookmarks.

MARGIN ICONS

The gray margin to the left of the line numbers contains icons giving information about the corresponding lines of code. The following table describes the icons on lines 3 through 11.

LINE

ICON

MEANING

3

Yellow arrow

Indicates that execution is paused at this line

4

Red circle

Indicates a breakpoint

5

Hollow red circle

Indicates a disabled breakpoint

6

Red circle with plus sign

Indicates a breakpoint with a condition or hit count test

10

Red diamond

Indicates a breakpoint that executes an action when reached

11

Blue and white rectangle

Indicates a bookmark

These icons can combine to indicate more than one condition. For example, line 12 shows a blue and white rectangle to indicate a bookmark, a hollow red diamond to indicate a disabled breakpoint that performs an action, and a plus sign to indicate that the breakpoint has a condition or hit count test.

Note that the editor marks some of these lines in other ways than just an icon. It highlights the currently executing line with a yellow background. It marks lines that hold enabled breakpoints with white text on a red background.

To add or remove a simple breakpoint, click in the gray margin.

To make a more complex breakpoint, click in the margin to create a simple breakpoint. Then right-click the breakpoint icon and select one of the context menu's commands. The following list describes these commands:

  • Delete Breakpoint — Removes the breakpoint.

  • Disable Breakpoint — Disables the breakpoint. When the breakpoint is disabled, this command changes to Enable Breakpoint.

  • Location — Lets you change the breakpoint's line number. Usually it is easier to click in the margin to remove the old breakpoint and then create a new one.

  • Condition — Lets you place a condition on the breakpoint. For example, you can make the breakpoint stop execution only when the variable num_employees has a value greater than 100.

  • Hit Count — Lets you set a hit count condition on the breakpoint. For example, you can make the breakpoint stop execution when it has been reached a certain number of times.

  • Filter — Lets you restrict the breakpoint so it is only set in certain processes or threads.

  • When Hit — Lets you specify the action that the breakpoint performs when it triggers. For example, it might display a message in the Output window or run a macro.

  • Edit Labels — Lets you add labels to a breakpoint. Later you can select this option to view, change, or remove the breakpoint's labels.

  • Export — Lets you export information about the breakpoint into an XML file.

To add or remove a bookmark, place the cursor on a line and then click the Toggle Bookmark tool. You can find this tool, which looks like the blue and white bookmark icon, in the Text Editor toolbar (under the mouse in Figure 6-1) and at the top of the Bookmarks window. Other bookmark tools let you move to the next or previous bookmark, the next or previous bookmark in the current folder, or the next or previous bookmark in the current document. Others let you disable all bookmarks and delete a bookmark.

OUTLINING

By default, the code editor displays an outline view of code. If you look at the first line in Figure 6-1, you'll see a box with a minus sign in it just to the right of the line number. That box represents the outlining for the Form1 class. If you click this box, the editor collapses the class's definition and displays it as a box containing a plus sign. If you then click the new box, the editor expands the class's definition again.

The gray line leading down from the box leads to other code items that are outlined, and that you can expand or collapse to give you the least cluttered view of the code you want to examine. Near the bottom of Figure 6-1, you can see that the RandomizeArray subroutine has been collapsed. The ellipsis and rectangle around the routine name provide an extra indication that this code is hidden.

The editor automatically creates outlining entries for namespaces, classes and their methods, and modules and their methods. You can also use the Region statement to group a section of code for outlining. For example, you can place several related subroutines in a region so you can collapse and expand the routines as a group.

Figure 6-2 shows more examples of outlining. Line 36 begins a region named Randomization Functions that contains three collapsed subroutines. Notice that the corresponding End Region statement includes a comment that I added giving the region's name. This is not required but it makes the code easier to understand when you are looking at the end of a region.

The code editor outlines namespaces, classes and their methods, modules and their methods, and regions.

Figure 6.2. The code editor outlines namespaces, classes and their methods, modules and their methods, and regions.

Line 89 contains a collapsed region named Utility Functions.

Line 95 starts a module named HelperRoutines that contains one collapsed subroutine.

Finally, line 114 holds the collapsed ImageResources namespace.

Notice that the line numbers skip values for any collapsed lines. For example, the RandomizeIntegerArray subroutine is collapsed on line 38. This subroutine contains 15 lines (including the Sub statement), so the next visible line is labeled 53.

TOOLTIPS

If you hover the mouse over a variable at design time, the editor displays a tooltip describing the variable. For example, if you hover over an integer variable named num_actions, the tooltip displays "Dim num_actions As Integer."

If you hover over a subroutine or function call (not the routine's definition, but a call to it), the tooltip displays information about that routine. For example, if you hover over the RandomizeArray subroutine (which takes an array of integers as a parameter), the tooltip reads, "Private Sub RandomizeArray(arr() As Integer)."

At runtime, if you hover over a variable, the tooltip displays the variable's value. If the variable is complex (such as an array or structure), the tooltip displays the variable's name and a plus sign. If you click or hover over the plus sign, the tooltip expands to show the variable's members.

In Figure 6-3, the mouse hovered over variable arr. The editor displayed a plus sign and the text arr {Length = 100}. When the mouse hovered over the plus sign, the editor displayed the values shown in the figure. Moving the mouse over the up and down arrows at the top and bottom of the list makes the values scroll.

You can hover the mouse over a variable at runtime to see its value.

Figure 6.3. You can hover the mouse over a variable at runtime to see its value.

If a variable has properties that are references to other objects, you can hover over their plus signs to expand those objects. You can continue following the plus signs to drill into the variable's object hierarchy as deeply as you like.

INTELLISENSE

If you start typing a line of code, the editor tries to anticipate what you will type. For example, if you typed "Me." the editor would know that you are about to use one of the current object's properties or methods.

IntelliSense displays a list of the properties and methods that you might be trying to select. As you type more of the property or method, IntelliSense scrolls to show the choices that match what you have typed.

In Figure 6-4, the code includes the text "Me.Set", so IntelliSense is displaying the current object's methods that begin with the string "Set."

IntelliSense displays a list of properties and methods that you might be trying to type.

Figure 6.4. IntelliSense displays a list of properties and methods that you might be trying to type.

While the IntelliSense window is visible, you can use the up and down arrows to scroll through the list. While IntelliSense is displaying the item that you want to use, you can press the Tab key to accept that item and make IntelliSense type it for you. Press the Escape key to close the IntelliSense window and type the rest manually.

After you finish typing a method and its opening parenthesis, IntelliSense displays information about the method's parameters. Figure 6-5 shows parameter information for a form object's SetBounds method. This method takes four parameters: x, y, width, and height.

IntelliSense displays information about a method's parameters.

Figure 6.5. IntelliSense displays information about a method's parameters.

IntelliSense shows a brief description of the current parameter x. As you enter parameter values, IntelliSense moves on to describe the other parameters.

IntelliSense also indicates whether overloaded versions of the method exist. In Figure 6-5, IntelliSense is describing the first version of two available versions. You can use the up and down arrows on the left to move through the list of overloaded versions.

CODE COLORING AND HIGHLIGHTING

The code editor displays different types of code items in different colors (although they all appear black in this book). You can change the colors used for different items by selecting the Tools menu's Options command and opening the Environment

CODE COLORING AND HIGHLIGHTING

The following table describes some of the default colors that the code editor uses to highlight different code elements.

ITEM

HIGHLIGHTING

Comment

Green text

Compiler error

Underlined with a wavy blue underline

Keyword

Blue text

Other error

Underlined with a wavy purple underline

Preprocessor keyword

Blue text

Read-only region

Light gray background

Stale code

Purple text

User types

Navy text

Warning

Underlined with a wavy green underline

A few other items that may sometimes be worth changing have white backgrounds and black text by default. These include identifiers (variable names, types, object properties and methods, namespace names, and so forth), numbers, and strings.

When the code editor finds an error in your code, it highlights the error with a wavy underline. If you hover over the underline, the editor displays a tooltip describing the error. If Visual Studio can guess what you are trying to do, it adds a small flat rectangle to the end of the wavy error line to indicate that it may have useful suggestions.

The assignment statement i = "12" shown in Figure 6-6 has an error because it tried to assign a string value to an integer variable and that violates the Option Strict On setting. The editor displays the wavy error underline and a suggestion indicator because it knows a way to fix this error. The Error List window at the bottom also shows a description of the error.

If the code editor thinks it can figure out what's wrong, it displays a suggestion indicator.

Figure 6.6. If the code editor thinks it can figure out what's wrong, it displays a suggestion indicator.

If you hover over the suggestion indicator, the editor displays a tooltip describing the problem and an error icon. If you click the icon, Visual Studio displays a dialog box describing the error and listing the actions that you may want to take. Figure 6-7 shows the suggestion dialog box for the error in Figure 6-6. If you click the text over the revised sample code, or if you double-click the sample code, the editor makes the change.

The error suggestion dialog box proposes likely solutions to an error.

Figure 6.7. The error suggestion dialog box proposes likely solutions to an error.

CODE SNIPPETS

A code snippet is a piece of code that you might find useful in many applications. It is stored in a snippet library so that you can quickly insert it into a new application.

Visual Studio comes with hundreds of snippets for performing standard tasks. Before you start working on a complicated piece of code, you should glance at the snippets that are already available to you. In fact, it would be worth your time to use the Snippet Manager available from the Tools menu to take a good look at the available snippets right now before you start a new project. There's little point in reinventing methods for calculating statistical values if someone has already done it and given you the code.

Snippets are stored in simple text files with XML tags, so it is easy to share snippets with other developers. Go to the book's supplemental web page, www.vb-helper.com/vb_prog_ref.htm, to contribute snippets and to download snippets contributed by others.

The following sections explain how to use snippets in your applications and how to create new snippets.

Using Snippets

To insert a snippet, right-click where you want to insert the code and select Insert Snippet to make the editor display a list of snippet categories. Double-click a category to find the kinds of snippets that you want. If you select a snippet, a tooltip pops up to describe it. Figure 6-8 shows the editor preparing to insert the snippet named "Create a public property" from the "VB Prog Ref Snippets" category.

When you select a code snippet, a pop-up describes it.

Figure 6.8. When you select a code snippet, a pop-up describes it.

Double-click the snippet to insert it into your code.

The snippet may include values that you should replace in your code. These replacement values are highlighted with a light green background, and the first value is initially selected. If you hover the mouse over one of these values, a tooltip appears to describe the value. You can use the Tab key to jump between replacement values.

Figure 6-9 shows the inserted code for this example. The text "An Integer Property" is highlighted and selected. Other selected text includes "Integer," "0," and "MyProperty." The mouse is hovering over the value "An Integer Property," so the tooltip explains that value's purpose.

Values that you should replace in a snippet are highlighted.

Figure 6.9. Values that you should replace in a snippet are highlighted.

Creating Snippets

To create a new snippet, you need to build an XML file containing the property tags to define the snippet and any replacements that the user should make. To tell Visual Studio that the file contains a snippet, save it with a ".snippet" extension.

The following code shows the "Create a public property" snippet used in the previous section. The outer CodeSnippets and CodeSnippet tags are standard and you should not change them.

Use the Title tag in the Header section to describe the snippet.

Inside the Snippet tag, build a Declarations section describing any literal text that the user should replace. This example defines DataType, Description, DefaultValue, and PropertyName symbols. Each literal definition includes an ID, and can include a ToolTip and Description.

After the declarations, the Code tag contains the snippet's source code. The syntax <![CDATA[ . . .]]> tells XML processors to include any characters including carriage returns between the <![CDATA[ and the ]]> in the enclosing tag.

<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
      <CodeSnippet Format="1.0.0">
          <Header>
              <Title>Create a public property</Title>
          </Header>
          <Snippet>
              <Declarations>
                  <Literal>
                      <ID>DataType</ID>
                      <ToolTip>The property's data type.</ToolTip>
                       <Default>Integer</Default>
                   </Literal>
                   <Literal>
                       <ID>Description</ID>
                       <ToolTip>The property's description.</ToolTip>
                       <Default>An Integer property.</Default>
                   </Literal>
                   <Literal>
                       <ID>DefaultValue</ID>
                       <ToolTip>The property's default value.</ToolTip>
                       <Default>0</Default>
                   </Literal>
                   <Literal>
                       <ID>PropertyName</ID>
                       <ToolTip>The property's name.</ToolTip>
                       <Default>MyProperty</Default>
                   </Literal>
               </Declarations>
               <Code Language="VB">
                   <![CDATA[
      ' $Description$
      Private m_$PropertyName$ As $DataType$ = $DefaultValue$
      Public Property $PropertyName$() As $DataType$
          Get
             Return m_$PropertyName$
          End Get
          Set(ByVal value As $DataType$)
              m_$PropertyName$ = value
          End Set
      End Property
]]>
              </Code>
          </Snippet>
       </CodeSnippet>
   </CodeSnippets>

Create a directory to hold snippets and save the snippet's XML definition there. To tell Visual Studio where to look for your snippets, select the Tools menu's Code Snippets Manager command to display the tool shown in Figure 6-10. In the Language dropdown, select Visual Basic. Then click the Add button, browse to your snippet directory, and click OK. Now the directory and the snippets that it contains will be available in the Insert Snippet pop-ups.

The Code Snippets Manager lets you add and remove snippet directories.

Figure 6.10. The Code Snippets Manager lets you add and remove snippet directories.

ARCHITECTURAL TOOLS

The code editor provides several powerful new tools in Visual Basic 2010 that can help you understand the structure of your code and how to navigate through its pieces. They can give you a better understanding of how the pieces of the program fit together, and they can help you track down important code snippets, such as where a variable or type is defined and where one piece of code is called by others.

The following sections describe the most useful of these kinds of architectural tools and explain how to invoke them.

Rename

If you right-click the definition or occurrence of a symbol, such as a variable, subroutine, function, or class, and select Rename, Visual Studio displays a dialog where you can enter a new name for the item. If you enter a name and click OK, Visual Studio updates all references to that symbol. If the symbol is a variable, it changes all references to the variable so they use the new name.

This is much safer than using a simple textual find-and-replace, which can wreak havoc with strings that contain your target string. For example, if you textually replace the variable name "factor" with "issue," your Factorial function becomes Issueial. In contrast, if you right-click the "factor" variable, select Rename, and set the new name to "issue," Visual Studio only updates references to the variable.

Go To Definition

If you right-click a symbol or type, such as a variable, function, or class, and select Go To Definition, the code editor jumps to the location where the symbol is defined. For example, it would jump to a variable's declaration or a function's definition.

If the symbol you clicked is defined by Visual Basic or a library rather than your code, Visual Studio opens the Object Browser and displays the symbol's definition there.

Go To Type Definition

If you right-click a variable and click Go To Type Definition, the code editor jumps to the location where the symbol's data type is defined. For example, if you right-click a variable of type Employee, the editor would jump to the definition of the Employee class.

If you click a variable that has one of the pre-defined data types such as Integer, Double, or String, the editor displays the Object Browser entry for that type.

Highlight References

As of Visual Studio 2010, whenever the cursor sits on a symbol, the code editor highlights all references to that symbol by giving them a light gray background. It's a subtle effect, so you may not even notice it unless you know to look for it.

Reference highlighting makes it easier to see where a symbol such as a variable or subroutine is used, although it only really works locally. If a subroutine is called from many pieces of code that are far apart, you'll only see the ones that are currently visible in the code editor's window.

When you have a reference highlighted, you can use Ctrl+Shift+Up Arrow and Ctrl+Shift+Down Arrow to move to the next or previous reference.

To learn more about references to a symbol that are farther away, use the Find All References command described next.

Find All References

If you right-click a symbol such as a subroutine or variable and select "Find All References," Visual Studio displays a list of everywhere in the program that uses that symbol.

For example, if you right-click a call to a function named Fibonacci, the list includes all calls to that function and the function's definition.

You can double-click any of the listed references to make the code editor quickly jump to that reference.

Generate From Usage

As of Visual Studio 2010, the code editor can provide methods for automatically generating pieces of code. These come in the form of suggested error corrections.

For example, suppose you have not defined a Person class but you type the following code:

Dim new_student As New Person()

The code editor correctly flags this as an error because the Person class doesn't exist. It underlines the word Person with a blue squiggly line and displays a short red rectangle near it. If you hover over the rectangle, you'll see an error icon. If you then click the icon, Visual Studio displays a list of suggested corrections that include:

  • Change Person to Version

  • Generate 'Class Person'

  • Generate new type

The first choice assumes you have made a simple spelling error.

The second choice creates a new empty class named Person. You can fill in its properties and methods later.

The third choice displays the dialog shown in Figure 6-11 so you can make Person another data type that might make sense such as an Enum or Structure. The dialog lets you set the type's access to Default, Friend, or Public, and to specify the file where Visual Studio should create the new type.

The New Type dialog lets you create a new Class, Enum, or Structure.

Figure 6.11. The New Type dialog lets you create a new Class, Enum, or Structure.

Now suppose you type the following code:

new_student.FirstName = "Zaphod"

The code editor also flags this statement as an error. If you click the error icon this time, the suggested solution says:

Generate a property stub for 'FirstName' in 'WindowsApplication1.Person'

If you click this text, Visual Studio adds the following simple property to the Person class:

Property FirstName As String

The code editor can also generate a constructor for the class if you enter the following code:

Dim another_person As New Person("Trillian")

This code is flagged as an error because no constructor is defined that takes a parameter. The error suggestions can make a constructor for you, although you'll need to edit it to give it code that handles the parameter.

This also causes a new error because the class now has a constructor that takes a single parameter, but not one that takes no parameters, so the earlier statement Dim new_student As New Person() is flagged as an error.

By now you can probably guess what's coming: if you click the error icon, the suggestions can make a constructor for this case, too.

Similarly, you can use the error suggestions to generate stubs for subroutines and functions. Simply use the new items as if they already exist, use the error suggestions to build stubs, and then fill in the appropriate code.

THE CODE EDITOR AT RUNTIME

The code editor behaves slightly differently at runtime and design time. Many of its design-time features still work. Breakpoints, bookmarks, IntelliSense, and snippets still work.

At runtime, the editor adds new tools for controlling the program's execution. Right-click a value and select Add Watch or QuickWatch to examine and monitor the value. Use the Step Into, Step Over, and Step Out commands on the Debug menu or toolbar to make the program walk through the code. Hover the mouse over a variable to see a tooltip giving the variable's value (see the section "Tooltips" earlier in this chapter for more information).

Right-click a statement and select Show Next Statement to move the cursor to the next statement that the program will execute. Select Run To Cursor to make the program continue running until it reaches the cursor's current line.

Right-click and select Set Next Statement to make the program skip to a new location. You can also drag the yellow arrow indicating the next statement to a new location in the left margin.

By using all of these runtime features, you can walk through the code while it executes and learn exactly what it is doing at each step. You can see the values of variables, follow paths of execution through If Then statements, step in and out of routines, and run until particular conditions are met.

For more information on the Debug menu and its submenus, see the section "Debug" in Chapter 2, "Menus, Toolbars, and Windows." For more information on debugging techniques, see Chapter 7, "Debugging."

You can discover other runtime features by exploring the editor at runtime. Right-click different parts of the editor to see which commands are available in that mode.

SUMMARY

The Visual Basic code editor is one of the most important IDE windows for Visual Basic developers. Though you can use the Windows Forms Designer alone to place controls on a form, the form can't do much without code behind those controls.

The Visual Basic code editor lets you type code into a module, but it also does much more. It provides tooltips that let you view variable values; outlining that lets you expand and collapse code, so you can focus on your current task; IntelliSense that helps you remember what methods are available and what their parameters are; code coloring and highlighting that immediately flags errors; and code snippets that let you save and reuse complex pieces of code that perform frequent tasks. Architectural tools let you quickly find symbol and type definitions, jump to specific pieces of code, and easily see where a symbol is being used in the currently visible code. The code editor can even automatically generate stubs for classes, constructors, properties, and methods.

Many of these tools help you understand how the code works as you write it. Chapter 7, "Debugging," explains IDE tools that help you understand the code when it runs. Those tools let you walk through the code as it executes to see exactly what it is doing and what it is doing wrong.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.10.182