Call Methods at Design Time

Although Visual Studio .NET 2003 included the Immediate window, you couldn't use it to execute code at design time. Longtime VB coders missed this feature, which was a casualty of the lack of a background compiler. In Visual Studio 2005, this feature returns along with the return of a background compiler.

Note

Need to try out a freshly written code routine? Visual Studio 2005 lets you run it without starting your project.

How do I do that?

You can use the Immediate window to evaluate simple expressions, and even to run subroutines in your code. To try out this technique, add the following shared method to a class:

Public Shared Function AddNumbers(ByVal A As Integer, _
  ByVal B As Integer) As Integer
    
    Return A + B
    
End Sub

By making this a shared method, you ensure that it's available even without creating an instance of the class. Now, you can call it easily in the design environment.

By default, the Immediate window isn't shown at design time. To show it, select Debug → Windows → Command from the menu. Statements inside the Immediate window usually start with ? (a shorthand for Print, which instructs Visual Studio to display the result). You can enter the rest of the statement like any other line of code, with the benefit of IntelliSense. Figure 1-11 shows an example in which the Command window is used to run the shared method just shown.

Executing code at design time

Figure 1-11. Executing code at design time

When you execute a statement like the one shown in Figure 1-11, there will be a short pause while the background compiler works (and you'll see the message "Build started" in the status bar). Then the result will appear.

Note

The expression evaluation in the beta release of Visual Studio 2005 is a little quirky. Some evaluations won't work, and will simply launch your application without returning a result. Look for this to improve in future builds.

Where can I learn more?

The MSDN help includes more information about supported expression types at the index entry "expressions → about expressions."

Get Visual Basic 2005: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.