MSDN Magazine > Issues and Downloads > 2009 > July 2009 Issue >  Stay Error Free with Error Corrections In Visua...
Basic Instincts
Stay Error Free With Error Corrections
Dustin Campbell

This article is partly based on a prerelease version of Visual Studio. All information is subject to change.
One of the most useful features of the Microsoft Visual Basic editing experience in Microsoft Visual Studio is background compilation. You're probably already familiar with this feature, as it is similar in spirit to the spelling and grammar checker found in Microsoft Word. As you type code, the Visual Basic compiler runs in the background. When you type an error, it is underlined with a squiggle in the editor and added to the Error List window.
Prior to Visual Studio 2005, the only guidance for fixing errors came primarily from the error messages themselves. When possible, the Visual Basic Compiler generates error messages that are intended to explain not only what the error is, but also how to fix it.
Let's look at an example. Suppose that you have the following Visual Basic code:
Module Module1
  Sub Main()
    Dim i As Integer = "1"c
  End Sub
End Module
The code above produces a compiler error because it isn't clear which conversion from Char to Integer is expected. Should the compiler insert a conversion to produce the ASCII value of "1"c, or should it insert a conversion that produces the numerical value of "1"c? The compiler has no option but to generate this error message:
"'Char' values cannot be converted to 'Integer'. Use 'Microsoft.VisualBasic.AscW' to interpret a character as a Unicode value or 'Microsoft.VisualBasic.Val' to interpret it as a digit."
While the preceding error message goes to great lengths to explain how the problem can be fixed, it requires more coding on your part to actually fix it.

Introducing Error Corrections
To make fixing errors easier, the Error Correction UI was introduced. In Visual Studio 2005 and 2008, when an error is typed in the editor, a small red bar is added to the squiggle underline that indicates that a smart tag is available at that location, as shown in Figure 1.
Figure 1 Error Squiggle with a Smart Tag Indicator
If you hover the mouse over the smart tag indicator, the collapsed smart tag will appear along with a tooltip description. This is pictured in Figure 2.
Figure 2 Collapsed Smart Tag
In Figure 3, clicking on the smart tag expands the error correction UI with the options that are available for this particular code error.
Figure 3 Expanded Smart Tag with Available Error Corrections
The error correction UI makes it easy to fix errors quickly and accurately. The preview windows clearly show what changes will be made to your code, and it's a simple matter of clicking on either of the two hyperlinks to apply a fix.
Sometimes, a particular compiler is fixable in some cases, but not all. In these doubtful instances, the Visual Basic IDE will optimistically create a smart tag indicator for that error, primarily to improve performance. It is much quicker to create a smart tag indicator for errors that can be fixed some of the time than to check each error to determine if it can definitely be fixed before creating the indicator. When you hover over a smart tag indicator that doesn't have any error corrections, you will see the "no correction suggestions" message shown in Figure 4.
Figure 4 No Correction Suggestions

Applying Error Corrections with the Keyboard
Error corrections can be applied by using the keyboard as well as the mouse. If the editor caret is located on an error squiggle with a smart tag indicator, you can press Shift+Alt+F10 to immediately expand the smart tag and show the error correction options. With the smart tag expanded, the Up-Arrow and Down-Arrow keys will navigate the options and you can apply an error correction by pressing the Enter key. If you dislike the Shift+Alt+F10 keyboard shortcut, Ctrl+. will also display the smart tag. (I personally find Ctrl+. much easier to remember and to press!)

Fixing Invalid Code
Often, code will contain an error simply because it has an invalid structure. One common mistake is to write code that has unbalanced parentheses. Can you spot the error in the code below?
Module Module1
  Sub Main()
    Dim quad = Function(a, b, c) _
                 Function(x) (a * x * x) + (b * x) + c

    Dim f = quad(1.0, -79.0, 1601.0)

    Console.Write(f(42.0)
  End Sub
End Module
When code does not compile because it is invalid (e.g., the missing parenthesis in the call to Console.Write above), the Visual Basic IDE will suggest error corrections that make your code valid if applied. In Figure 5, the error correction offers to insert the missing parenthesis.
Figure 5 Error Correction for Inserting Parenthesis
Error corrections for invalid code aren't limited to code within a method body. For example, suppose that you have a read-only property and would like to convert it into a full property with a setter:
Class Person
  Private _name As String

  Public ReadOnly Property Name() As String
    Get
      Return _name
    End Get
  End Property
End Class
To add a setter in the code above, you would
  1. Move the editor caret after End Get.
  2. Press Enter.
  3. Type Set.
  4. Press Enter again.
That would leave you with the following invalid code:
Class Person
  Private _name As String

  Public ReadOnly Property Name() As String
    Get
      Return _name
    End Get
    Set(ByVal value As String)

    End Set
  End Property
End Class
To make the property valid, the ReadOnly keyword needs to be removed. Now, deleting the keyword is trivial, but it is easier and more efficient if you use the error correction to do the job:
  1. Press Up to move the editor caret to the error squiggle.
  2. Press Ctrl+. to display the suggestion error corrections shown in Figure 6.
  3. Press Down to focus the first error correction.
  4. Press Enter to apply.
Figure 6 Error Corrections for a Read-only Property with a Setter
As you can see, not only do error corrections help you write the correct code, they can be a big time saver!

Using the Right Type Conversions
By default, Visual Basic leaves strict typing off. This allows you to take advantage of the Visual Basic compiler's support for implicit data type conversions and late binding:
Module Module1
  Sub Main()
    Dim s As String = 42
  End Sub
End Module
Given the code above, the compiler will properly insert a type conversion from Integer to String.
However, if you use strict typing, Visual Basic error corrections will be available to help you insert the same type conversion that the compiler would have, if strict typing were off. Figure 7 shows the error correction for the code above when strict typing is enabled.
Figure 7 Error Correction to Convert an Integer to a String

Correcting Spelling Mistakes
Sometimes a code error might simply be a spelling mistake. For spelling errors in type names, Visual Basic will provide error corrections that suggest existing types with similar names. Consider the following code, which contains a spelling mistake:
Class Class1
End Class

Class Class2
End Class

Module Module1
  Sub Main()
    Dim c As New Clss
  End Sub
End Module
The code above mistakenly attempts to instantiate a type named Clss, but none exists. In this situation, two error corrections are available, one to change Clss to Class1 and another to change Clss to Class2, as shown in Figure 8.
Figure 8 Error Correction for Spelling Mistake
Currently, the spell checker is fairly simple and works only for type names. However, this is an area that the Visual Basic team would like to improve in a future release.

Importing Namespaces
After shipping Visual Studio 2005, the Visual Basic team received several requests for additional error corrections. Chief among these was an error correction for automatically adding Imports statements. It can be pretty irritating to start using a type and realize that you've forgotten to import its namespace. For example, suppose you were using the System.IO.File class to open and read a file from disk:
Module Module1
  Sub Main()
    Dim fileName = Path.Combine("C:\Temp", "Sizes.txt")
    Using f = File.OpenRead(fileName)

    End Using
  End Sub
End Module
This code results in an error if you haven't imported the System.IO namespace yet. In Visual Studio 2008, there are two possible error corrections for this error:
  1. Import the namespace.
  2. Qualify the reference.
This is shown in Figure 9. By choosing the first suggested error correction, we can easily import the System.IO namespace.
Figure 9 Error Correction for Adding Imports Statements
This begs the question: what if importing a namespace would change the meaning of your code? Suppose that the code above will use the Windows Presentation Framework (WPF) to create a System.Windows.Shapes.Rectangle, using data read from the Sizes.txt file. With the WPF references added, you start by instantiating a new Rectangle:
Imports System.IO

Module Module1
  Sub Main()
    Dim fileName = Path.Combine("C:\Temp", "Sizes.txt")
    Using f = File.OpenRead(fileName)
      Dim r As New Rectangle
    End Using
  End Sub
End Module
Like before, the namespace hasn't been imported yet, so you use the error correction UI pictured in Figure 10 to import it for you. However, this time there's a problem. The System.Windows.Shapes namespace also includes a type named Path, so importing the namespace would change the meaning of your code.
Figure 10 Error Corrections for Importing System.Windows.Shapes
Fortunately, the logic to avoid these situations is built into the error correction for adding Imports statements. The error correction recognizes the problem and displays the Add Imports Validation Error dialog, pictured in Figure 11.
Figure 11 The Add Imports Validation Error Dialog
This dialog gives you two options for tweaking the error correction, so the meaning of your code isn't changed:
  1. Import 'System.Windows.Shapes' and qualify the affected identifiers.
  2. Do not import 'System.Windows.Shapes', but change 'Rectangle' to 'Windows.Shapes.Rectangle'.
By picking the first option, an Imports statement is added for System.Windows.Shapes, and the reference to Path is fully qualified:
Imports System.IO
Imports System.Windows.Shapes

Module Module1
  Sub Main()
    Dim fileName = System.IO.Path.Combine("C:\Temp", "Sizes.txt")
    Using f = File.OpenRead(fileName)
      Dim r As New Rectangle
    End Using
  End Sub
End Module
Again, this error correction is available only in Visual Studio 2008. If you are using Visual Studio 2005, you won't see suggestions for adding Imports statements.

Generating New Types and Members
Visual Basic isn't done with error corrections yet! Visual Studio 2010 will introduce a new feature called Generate from Usage, which allows you to easily generate new types and members. For Visual Basic, this feature is implemented as a set of error corrections, so you can access them through the existing error corrections. In many cases, the Generate from Usage error corrections offer suggestions for compiler errors that previously had none. For example, look back at Figure 4. In Visual Studio 2008, that code has no error corrections available. But in Visual Studio 2010, the new Generate from Usage error corrections are suggested. Figure 12 shows the difference in the error corrections between Visual Studio 2008 and Visual Studio 2010 for the same code.
Figure 12 Generate Class
By choosing the first suggestion, a new class named Customer is generated in a new file. Now, you can continue to write code that uses members of the Customer class and use the error corrections to stub out the members for you. For example, Figure 13 shows the error corrections after you've assigned a value to a member of a class that hasn't been declared yet.
Figure 13 Generate Property or Field
After choosing the first suggestion, the generated Customer class looks like this:
Class Customer
  Property Name As String
End Class
In Visual Studio 2010, you will be able to leverage the Generate from Usage error corrections for maximum efficiency.

Conclusion
Error corrections are an essential part of the Visual Basic coding experience. Not only do they help you immediately spot and fix errors, but you can use them to write code more efficiently. This article only scratches the surface of the hundreds of suggestions offered by Visual Basic. And with Visual Studio 2010, there is an error correction for most coding errors.
Don't forget to use Ctrl+.!

Send your questions and comments to instinct@microsoft.com.

Dustin Campbell is the Microsoft Visual Basic IDE Program Manager on the Microsoft Visual Studio Languages Team. He works primarily on the editor and debugger product features. As a programming language nut, he also contributes to other languages in Visual Studio, such as C# and F#. Before joining Microsoft, Dustin helped to develop the award-winning CodeRush and Refactor! tools at Developer Express Inc. Dustin's favorite color is blue.

Page view tracker