Running Code at Design Time from the Immediate Window
Back in Visual Basic 6.0, developers were able to evaluate expressions from the Immediate Window at design time (we’ll call this feature ‘DTEE’ – Design Time Express Evaluation from now on). This feature gave the developer an opportunity to test their code out and to debug their functions without having to run their entire application first and it was a handy development feature which was not available in Visual Basic 2002 and 2003.
Visual Basic 2005 has brought this feature back to the VB Developer and here is a quick blurb on what you can do with DTEE.
Note: DTEE is available for all of the Visual Basic Windows project types. If DTEE is not available for the project type you have opened in the IDE, you will get the following message in the Immediate Window when you try and evaluate an expression: “The expression cannot be evaluated while in design mode.”
Let’s try it out!
- Create a new Visual Basic Class Library project and name it ‘MyMathLibrary’
(New to Visual Basic 2005, we are now able to evaluate expressions in a Class Library which was not directly possible in Visual Basic 6.0)
- Once the project is created, paste the following code somewhere inside of Class1’s code block:
Function Square(ByVal num1 As Integer) As Long
Return num1 * num1
Function Fib(ByVal n As Long) As Long
If n <= 1 Then
Fib = n
Fib = Fib(n – 1) + Fib(n – 2)
To open the Immediate Window, for those of you using the Visual Basic Development settings simply press Ctrl-G. Or from the Debug menu, click Windows and then select Immediate.
The Immediate Window should now be open
- Let’s evaluate the function ‘Square’ at design time.
- From the Immediate Window, you can instantiate a new instance of Class1 by assigning it to an implicit variable. To do so type the following and then hit <RETURN>
x = New Class1
- This creates an instance of Class1 called ‘x’.
- Now evaluate the function ‘Square’ by calling it off of the newly created instance of Class1. To do so, type the following and then hit <RETURN>
- You will see the result ‘144’ from the evaluation in the immediate window
You can also evaluate other methods off of the existing class instance ‘x’
Try it out and let us know what you think of DTEE in Visual Basic 2005!