One of the advantages of using an Integrated Development Environment (IDE) over a plain text editor is that it's designed to help you be more productive and efficient by enabling you to write code faster. Two of Visual Studio 2010's most powerful features that help increase your productivity are its support for code snippets and the refactoring tools that it provides.
Code snippets are small chunks of code that can be inserted into an application's code base and then customized to meet the application's specific requirements. They do not generate full-blown applications or whole files, unlike project and item templates. Instead, code snippets are used to insert frequently used code structures or obscure program code blocks that are not easy to remember. In the first part of this chapter you see how using code snippets can improve your coding efficiency enormously.
This chapter also focuses on Visual Studio 2010's refactoring tools — refactoring being the process of reworking code to improve it without changing its functionality. This might entail simplifying a method, extracting a commonly used code pattern, or even optimizing a section of code to make it more efficient.
Although refactoring tools are implemented for C# in Visual Studio, unfortunately they haven't been implemented for VB. In order to fill this hole in functionality in previous versions of Visual Studio, Microsoft licensed the VB version of Refactor! from Developer Express. For Visual Studio 2010, CodeRush Xpress (also from Developer Express) takes over from Refactor! to implement refactoring for VB. Even though Microsoft has licensed CodeRush Xpress, it still needs to be downloaded and installed separately from Visual Studio (as an add-in). You can download it from the VB developer center at http://msdn.microsoft.com/vbasic/;
follow the links to Downloads, then Tools and Utilities.
CodeRush Xpress provides a range of additional refactoring support that complements the integrated support available for C# developers. However, this chapter's discussion is restricted to the built-in refactoring support provided within Visual Studio 2010 (for C# developers) and the corresponding action in CodeRush Xpress (for VB developers).
Code snippets have been around in a variety of forms for a long time but generally required third-party add-ins for languages such as VB 6 and the early versions of Visual Studio. Visual Studio 2010 includes extensive code snippet support that allows a block of code along with predefined replacement variables to be inserted into a file, making it easy to customize the inserted code to suit the task at hand.
Before looking at code snippets, this section looks at the simplest means Visual Studio provides to insert predefined blocks of text into a file. Much like it can hold controls to be inserted on a form, the Toolbox can also hold blocks of text (such as code) that can be inserted into a file. To add a block of code (or other text) to the Toolbox, simply select the text in the editor and drag it over onto the Toolbox. This creates an entry for it in the Toolbox with the first line of the code as its name. You can rename, arrange, and group these entries like any other element in the Toolbox. To insert the code block you simply drag it from the Toolbox to the desired location in a file as shown in Figure 8-1, or simply double-click the Toolbox entry to insert it at the current cursor position in the active file.
Many presenters use this simple feature to quickly insert large code blocks when writing code live in presentations.
This is the simplest form of "code snippet" behavior in Visual Studio 2010, but with its simplicity comes limited functionality, such as the lack of ability to modify and share them. Nevertheless, this method of keeping small sections of code can prove useful in some scenarios to maintain a series of code blocks for short-term use.
Now we come to a much more useful way to insert blocks of code into a file: code snippets. Code snippets are defined in individual XML files, each containing a block of code that programmers may want to insert into their code, and may also include replaceable parameters making it easy to then customize the inserted snippet for the current task. They are integrated with Visual Studio's IntelliSense, making them very easy to find and insert into a code file.
VB code snippets also have the ability to add assembly references and insert Imports
statements.
Visual Studio 2010 ships with many predefined code snippets for the two main languages, VB and C#, along with snippets for JavaScript, HTML, and XML. These snippets are arranged hierarchically in a logical fashion so that you can easily locate the appropriate snippet. Rather than locate the snippet in the Toolbox, you can use menu commands or keyboard shortcuts to bring up the main list of groups.
In addition to the predefined code snippets, you can create your own code snippets and store them in this code snippet library. Because each snippet is stored in a special XML file, you can even share them with other developers.
Following are three scopes under which a snippet can be inserted:
Class Declaration: The snippet actually generates an entire class.
Member Declaration: This snippet scope includes code that defines members, such as methods, properties, and event handler routines. This means it should be inserted outside an existing member.
Member Body: This scope is for snippets that are inserted into an already defined member, such as a method.
Insert Snippet is a special kind of IntelliSense that appears inline in the code editor. Initially, it displays the words "Insert Snippet" along with a drop-down list of code snippet groups from which to choose. Once you select the group that contains the snippet you require (using up and down arrows, followed by the Tab key), it shows you a list of snippets, and you can simply double-click the one you need (alternatively, pressing Tab or Enter with the required snippet selected has the same effect).
To insert a code snippet in C#, simply locate the position where you want to insert the generated code, and then the easiest way to bring up the Insert Snippet list is to use the keyboard shortcut combination of Ctrl+K, Ctrl+X. You have two additional methods to start the Insert Snippet process. The first is to right-click at the intended insertion point in the code window and select Insert Snippet from the context menu that is displayed. The other option is to use the Edit
At this point, Visual Studio brings up the Insert Snippet list, as Figure 8-2 demonstrates. As you scroll through the list and hover the mouse pointer over each entry, a tooltip is displayed to indicate what the snippet does and a shortcut that can be used to insert it.
To use the shortcut for a code snippet, simply type it into the code editor (note that it appears in the IntelliSense list) and press the Tab key twice to insert the snippet at that position.
Figure 8-3 displays the result of selecting the Automatically Implemented Property snippet. To help you modify the code to your own requirements, the sections you would normally need to change (the replacement variables) are highlighted, with the first one conveniently selected.
When you are changing the variable sections of the generated code snippet, Visual Studio 2010 helps you even further. Pressing the Tab key moves to the next highlighted value, ready for you to override the value with your own. Shift+Tab navigates backward, so you have an easy way of accessing the sections of code that need changing without needing to manually select the next piece to modify. Some code snippets use the same variable for multiple pieces of the code snippet logic. This means changing the value in one place results in it changing in all other instances.
To hide the highlighting of these snippet variables once you are done you can simply continue coding, or press either Enter or Esc.
Code snippets in VB have additional features over what is available in C#, namely the ability to automatically add references to assemblies in the project, and insert Imports
statements into a file that the code needs in order to compile.
To use a code snippet you should first locate where you want the generated code to be placed in the program listing and position the cursor at that point. You don't have to worry about the associated references and Imports
statements; they will be placed in the correct location. Then, as with C# snippets, you can use one of the following methods to display the Insert Snippet list:
Use the keyboard chord Ctrl+K, Ctrl+X
Right-click and choose Insert Snippet from the context menu
Run the Edit
VB also has an additional way to show the Insert Snippet List: simply type ?
and press Tab.
Let's navigate through the hierarchy and insert a snippet named Draw a Pie Chart. Figure 8-4 demonstrates how you might navigate through the hierarchy to find the snippet and insert it into your project.
You might have noticed in Figure 8-4 that the tooltip text includes the words "Shortcut: drawPie." This text indicates that the selected code snippet has a text shortcut that you can use to automatically invoke the code snippet behavior without navigating the code snippet hierarchy. As with C# all you need to do is type the shortcut into the code editor and press the Tab key once for it to be inserted. In VB the shortcut isn't case-sensitive, so this example can be generated by typing the term "drawpie" and pressing Tab. Note that shortcuts don't appear in IntelliSense in VB as they do in C#.
After inserting the code snippet, if it contains replacement variables you can enter their values then navigate between these by pressing Tab as described for C#. To hide the highlighting of these snippet variables once you are done, you can simply continue coding, or right-click and select Hide Snippet Highlighting. If you want to highlight all the replacement variables of the code snippets inserted since the file was opened, right-click and select Show Snippet Highlighting.
The last refactoring action, available in C# (and VB with CodeRush Xpress), is the capability to surround an existing block of code with a code snippet. For example, to wrap an existing block with a conditional try-catch block, right-click and select Surround With, or select the block of code and press Ctrl+K, Ctrl+S. This displays the Surround With dialog that contains a list of surrounding snippets that are available to wrap the selected line of code, as shown in Figure 8-5.
Selecting the try
snippet results in the following code:
Public Sub MethodXYZ(ByVal name As String)
Try
MessageBox.Show(name)
Catch ex As Exception
Throw
End Try
End Sub
public void MethodXYZ(string name) {try
{
MessageBox.Show(name);}
catch (Exception)
{
throw;
}
}
The Code Snippets Manager is the central library for the code snippets known to Visual Studio 2010. You can access it via the Tools
When it is initially displayed, the Code Snippets Manager shows the HTML snippets available, but you can change it to display the snippets for the language you are using via the Language drop-down list. Figure 8-6 shows how it looks when you're editing a C# project. The hierarchical folder structure follows the same set of folders on the PC by default, but as you add snippet files from different locations and insert them into the different groups, the new snippets slip into the appropriate folders.
If you have an entire folder of snippets to add to the library, such as when you have a corporate setup and need to import the company-developed snippets, you use the Add button. This brings up a dialog that you use to browse to the required folder. Folders added in this fashion appear at the root level of the tree — on the same level as the main groups of default snippets. However, you can add a folder that contains subfolders, which will be added as child nodes in the tree.
Removing a folder is just as easy — in fact, it's dangerously easy. Select the root node that you want to remove and click the Remove button. Instantly, the node and all child nodes and snippets are removed from the Snippets Manager without a confirmation window. If you do this by accident you are best off clicking the Cancel button and opening the dialog again. If you've made changes you don't want to lose, you can add them back by following the steps explained in the previous walkthrough, but it can be frustrating trying to locate a default snippet folder that you inadvertently deleted from the list.
The location for the code snippets that are installed with Visual Studio 2010 is deep within the installation folder. By default, the code snippet library when running on 32-bit Windows is installed in %programfiles%Microsoft Visual Studio 10.0VBSnippets1033
for VB snippets and %programfiles%Microsoft Visual Studio 10.0VC#Snippets1033
for C# (for 64-bit Windows, replace %programfiles%
with %programfiles(x86)%)
. Individual snippet files can be imported into the library using the Import button. The advantage of this method over the Add button is that you get the opportunity to specify the location of each snippet in the library structure.
Visual Studio 2010 does not ship with a code snippet creator or editor. However, Bill McCarthy's Snippet Editor allows you to create, modify, and manage your snippets (including support for VB, C#, HTML, JavaScript, and XML snippets). Starting as an internal Microsoft project, the Snippet Editor is now an open source project hosted on CodePlex where Bill fixed the outstanding issues and proceeded to add functionality. With the help of other MVPs it is now also available in a number of different languages. You can download the snippet editor from http://snippeteditor.codeplex.com
.
Creating code snippets by manually editing the .snippet
XML files can be a tedious and error-prone process, so the Snippet Editor makes it a much more pleasant experience. When you start the Snippet Editor you will notice a drop-down list in the top left-hand corner — make sure you select Visual Studio 2010. Below this is a tree containing all the snippets known to Visual Studio 2010. By expanding a node you'll see a set of folders similar to those in the code snippet library (see Figure 8-7).
An excellent feature of the Snippet Editor is the view it offers of the structure of any snippet file in the system. This means you can browse the default snippets installed with Visual Studio, which can provide insight into how to better build your own snippets.
Browse to the snippet you're interested in and double-click its entry to display it in the Editor window. Figure 8-7 shows a simple snippet to Display a Windows Form. Four main panes contain all the associated information about the snippet. From top to bottom, these panes are described in Table 8-1.
Table 8.1. Information Panes for Snippets
PANE | FUNCTION |
---|---|
Properties | The main properties for the snippet, including title, shortcut, and description. |
Code | Defines the code for the snippet, including all Literal and Object replacement regions. |
References | If your snippet will require assembly references, this tab enables you to define them. |
Imports | Similar to the References tab, this tab enables you to define any |
Browsing through these tabs enables you to analyze an existing snippet for its properties and replacement variables. In the example shown in Figure 8-7, there is a single replacement region with an ID of formName
and a default value of "Form"
.
To demonstrate how the Snippet Editor makes creating your own snippets straightforward, follow this next exercise, in which you create a snippet that creates three subroutines, including a helper subroutine:
Start the Snippet Editor and create a new snippet. To do this, select a destination folder in the tree, right-click, and select Add New Snippet from the context menu that is displayed.
When prompted, name the snippet "Create A Button Sample" and click OK. Double-click the new entry to open it in the Editor pane.
Note that creating the snippet does not automatically open the new snippet in the Editor — don't overwrite the properties of another snippet by mistake!
The first thing you need to do is edit the Title
, Description
, and Shortcut
fields (see Figure 8-8):
Title
: Create A Button Sample
Description
: This snippet adds code to create a button control and hook an event handler to it
Shortcut
: CreateAButton
Because this snippet contains member definitions, set the Type to "Member Declaration."
In the Editor window, insert the code necessary to create the three subroutines:
Private Sub CreateButtonHelper CreateAButton(controlName, controlText, Me) End Sub Private Sub CreateAButton(ByVal ButtonName As String, _ ByVal ButtonText As String, _ ByVal Owner As Form) Dim MyButton As New Button MyButton.Name = ButtonName
MyButton.Text = ButtonName Owner.Controls.Add(MyButton) MyButton.Top = 0 MyButton.Left = 0 MyButton.Text = ButtonText MyButton.Visible = True AddHandler MyButton.Click, AddressOf ButtonClickHandler End Sub Private Sub ButtonClickHandler(ByVal sender As System.Object, _ ByVal e As System.EventArgs) MessageBox.Show("The " & sender.Name & " button was clicked") End Sub
private void CreateButtonHelper() { CreateAButton(controlName, controlText, this); } private void CreateAButton(string ButtonName, string ButtonText, Form Owner) { Button MyButton = new Button(); MyButton.Name = ButtonName; MyButton.Text = ButtonName; Owner.Controls.Add(MyButton); MyButton.Top = 0; MyButton.Left = 0; MyButton.Text = ButtonText; MyButton.Visible = true; MyButton.Click += MyButton_Click; } private void MyButton_Click(object sender, EventArgs e) { MessageBox.Show("The " + sender.Name + " button was clicked");
You will notice that your code differs from that shown in Figure 8-8 in that the word controlName
does not appear highlighted. In Figure 8-8, this argument has been made a replacement region. You can do this by selecting the entire word, right-clicking, and selecting Add Replacement (or alternatively, clicking the Add button in the area below the code window).
Change the replacement properties like so:
ID
: controlName
Defaults to
: "MyButton"
Tooltip
: The name of the button
Repeat this for controlText
:
ID
: controlText
Defaults to
: "Click Me!"
Tooltip
: The text property of the button
Your snippet is now done and ready to be used. You can use Visual Studio 2010 to insert the snippet into a code window.
There are a number of ways to invoke the refactoring tools in Visual Studio 2010, including from the right-click context menu, smart tags, and the Refactor menu in the main menu (for C# developers only).
Figure 8-9 shows the Refactor context menu available for C# developers. The full list of refactoring actions available to C# developers within Visual Studio 2010 includes Rename, Extract Method, Encapsulate Field, Extract Interface, Promote Local Variable to Parameter, Remove Parameters, and Reorder Parameters. You can also use Generate Method Stub and Organize Usings, which can be loosely classified as refactoring.
The built-in refactoring support provided by Visual Studio 2010 for VB developers is limited to the symbolic Rename and Generate Method Stub. Additional refactoring support for VB developers is provided by CodeRush Xpress, which can be accessed via the right-click context menu (which dynamically changes so that only valid refactoring actions are displayed), or via the smart tags (as shown in Figure 8-10) that it displays when a refactoring is available for the current selection (which can be clicked, or activated by pressing Ctrl+`).
CodeRush Xpress adds support for all of the refactoring tools that C# has, and it adds many more (to both languages). Examples of additional refactorings include Create Overload, Flatten Conditional, Inline Temp, Introduce Constant, Introduce Local, Move Declaration Near Reference, Move Initialization to Declaration, Remove Assignments to Parameters, Rename, Reorder Parameters, Replace Temp with Query, Reverse Conditional, Safe Rename, Simplify Expression, Split Initialization from Declaration, and Split Temporary Variable.
The following sections describe each of the refactoring options and provide examples of how to use built-in support for both C# and CodeRush Xpress for VB.
One of the best ways to start refactoring a long method is to break it up into several smaller methods. The Extract Method refactoring action is invoked by selecting the region of code you want moved out of the original method and selecting Extract Method from the context menu. In C#, this will prompt you to enter a new method name, as shown in Figure 8-11. If there are variables within the block of code to be extracted that were used earlier in the original method, they automatically appear as variables in the method signature. Once the name has been confirmed, the new method is created immediately after the original method. A call to the new method replaces the extracted code block.
For example, in the following code snippet, if you wanted to extract the conditional logic into a separate method, you would select the code, shown in bold, and choose Extract Method from the right-click context menu:
C#
private void button1_Click(object sender, EventArgs e) { string connectionString = Properties.Settings.Default.ConnectionString;if (connectionString == null)
{
connectionString = "DefaultConnectionString";
}
MessageBox.Show(connectionString); /* ... Much longer method ... */ }
This would automatically generate the following code in its place:
C#
Private void button1_Click(object sender, EventArgs e) {
string connectionString = Properties.Settings.Default.ConnectionString;connectionString = ValidateConnectionString(output);
MessageBox.Show(connectionString); /* ... Much longer method ... */ }private static string ValidateConnectionString(string connectionString)
{
if (connectionString == null)
{
connectionString = "DefaultConnectionString";
}
return connectionString;
}
CodeRush Xpress handles this refactoring action slightly differently for VB developers. After you select the code you want to replace, CodeRush Xpress prompts you to select a place in your code where you want to insert the new method. This can help developers organize their methods in groups, either alphabetically or according to functionality.
Figure 8-12 illustrates the aid that appears which enables you to position where the method should be inserted using the cursor keys.
After selecting the insert location, CodeRush Xpress inserts the new method, giving it an arbitrary name. In doing so it highlights the method name, enabling you to rename the method either at the insert location or where the method is called (see Figure 8-13).
Using the Extract Method refactoring on the following code:
VB
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connectionString As String = My.MySettings.Default.ConnectionString
If connectionString Is Nothing Then
connectionString = "DefaultConnectionString"
End If
MessageBox.Show(connectionString)
'Much longer method
End Sub
And renaming the method to give it an appropriate name will result in the following code:
VB
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connectionString As String = My.MySettings.Default.ConnectionStringValidateConnectionString(connectionString)
MessageBox.Show(connectionString) 'Much longer method End SubPrivate Shared Sub ValidateConnectionString(ByRef connectionString As String)
If connectionString Is Nothing Then connectionString = "DefaultConnectionString" End If End Sub
Another common task when refactoring is to encapsulate an existing class variable with a property. This is what the Encapsulate Field refactoring action does. To invoke this action, select the variable you want to encapsulate and then choose the appropriate refactoring action from the context menu. This gives you the opportunity to name the property and elect where to search for references to the variable, as shown in Figure 8-14.
The next step after specifying the new property name is to determine which references to the class variable should be replaced with a reference to the new property. Figure 8-15 shows the preview window that is returned after the reference search has been completed. In the top pane is a tree indicating which files and methods have references to the variable. The checkbox beside each row indicates whether a replacement will be made. Selecting a row in the top pane brings that line of code into focus in the lower pane. Once each of the references has been validated, the encapsulation can proceed. The class variable is updated to be private, and the appropriate references are also updated.
The Encapsulate Field refactoring action using CodeRush Xpress works in a similar way, except that it automatically assigns the name of the property based on the name of the class variable. The interface for updating references is also different, as shown in Figure 8-16. Instead of a modal dialog, CodeRush Xpress presents a visual aid that can be used to navigate through the references (or you can navigate between references using the Tab key). Where a replacement is required, click the check mark or press Enter. Unlike the C# dialog box, in which the checkboxes can be checked and unchecked as many times as needed, once you accept a replacement there is no way to undo this action.
As a project goes from prototype or early-stage development to a full implementation or growth phase, it's often necessary to extract the core methods for a class into an interface to enable other implementations or to define a boundary between disjointed systems. In the past you could do this by copying the entire method to a new file and removing the method contents so you were just left with the interface stub. The Extract Interface refactoring action enables you to extract an interface based on any number of methods within a class. When this refactoring action is invoked on a class, the dialog in Figure 8-17 is displayed, which enables you to select which methods are included in the interface. Once selected, those methods are added to the new interface. The new interface is also added to the original class.
In the following example, the first method needs to be extracted into an interface:
C#
public class ConcreteClass { public void ShouldBeInInterface()
{ /* ... */ } public void AnotherNormalMethod(int ParameterA, int ParameterB) { /* ... */ } public void NormalMethod() { /* ... */ } }
Selecting Extract Interface from the right-click context menu and selecting only the ShouldBeInInterface
method to be extracted from the Extract Interface dialog introduces a new interface (in a new file) and updates the original class as follows:
C#
interface IBestPractice { void ShouldBeInInterface(); } public class ConcreteClass: Chapter08Sample.IBestPractice { public void ShouldBeInInterface() { /* ... */ } public void NormalMethod(int ParameterA, int ParameterB) { /* ... */ } public void AnotherNormalMethod() { /* ... */ } }
Extracting an interface is also available within CodeRush Xpress, however it doesn't allow you to choose which methods you want to include in the interface. Unlike the C# interface extraction, which places the interface in a separate file (which is recommended), CodeRush Xpress simply extracts all public class methods into an interface in the same code file. For example, using CodeRush Xpress's Extract Interface refactoring action on the following class:
VB
Public Class ConcreteClass Public Sub ShouldBeInInterface() '... End Sub Public Sub NormalMethod(ByVal ParameterA As Integer, ByVal ParameterB As Integer) '... End Sub Public Sub AnotherNormalMethod() '... End Sub End Class
Will result in the following code:
VB
Public Interface IConcreteClass Sub ShouldBeInInterface() Sub NormalMethod(ByVal ParameterA As Integer, ByVal ParameterB As Integer) Sub AnotherNormalMethod() End Interface Public Class ConcreteClass Implements IConcreteClass Public Sub ShouldBeInInterface() Implements IConcreteClass.ShouldBeInInterface '... End Sub Public Sub NormalMethod(ByVal ParameterA As Integer, ByVal ParameterB As Integer) _ Implements IConcreteClass.NormalMethod '... End Sub Public Sub AnotherNormalMethod() Implements IConcreteClass.AnotherNormalMethod '... End Sub End Class
Sometimes it's necessary to reorder parameters. This is often for cosmetic reasons, but it can also aid readability and is sometimes warranted when implementing interfaces. The Reorder Parameters dialog, shown in Figure 8-18, enables you to move parameters up and down in the list according to the order in which you want them to appear.
Once you establish the correct order, you're given the opportunity to preview the changes. By default, the parameters in every reference to this method are reordered according to the new order. The Preview dialog, similar to the one shown in Figure 8-15, enables you to control which references are updated.
The CodeRush Xpress experience for reordering parameters is somewhat more intuitive than the native action for C#. Again, the creators have opted for visual aids instead of a modal dialog, as shown in Figure 8-19. You can move the selected parameter left or right in the parameter list and navigate between parameters with the Tab key. Once the parameters are in the desired order, the search and replace interface, illustrated in Figure 8-16, enables the developer to verify all updates.
When removing a parameter from a method, using the refactoring function to do this considerably reduces the amount of searching that has to be done for compile errors that can occur when a parameter is removed. The other time this action is particularly useful is when there are multiple overloads for a method, and removing a parameter may not generate compile errors; in such a case, runtime errors may occur due to semantic, rather than syntactical, mistakes.
Figure 8-20 illustrates the Remove Parameters dialog that is used to remove parameters from the parameters list. If a parameter is accidentally removed, it can be easily restored until the correct parameter list is arranged. As the warning on this dialog indicates, removing parameters can often result in unexpected functional errors, so it is important to review the changes made. Again, you can use the preview window to validate the proposed changes.
CodeRush Xpress only supports removing unused parameters, as shown in Figure 8-21.
Visual Studio 2010 provides rename support in both C# and VB. The Rename dialog for C# is shown in Figure 8-22; it is similar in VB although it doesn't have the options to search in comments or strings.
Unlike the C# rename support, which displays the preview window so you can confirm your changes, the rename capability in VB simply renames all references to that variable.
One of the most common refactoring techniques is to adapt an existing method to accept an additional parameter. Promoting a method variable to a parameter makes the method more generic. It also promotes code reuse. Intuitively, this operation would introduce compile errors wherever the method was referenced. However, the catch is that the variable you are promoting to a parameter must have an initial constant value. This value is added as a parameter value to all the method references to prevent any changes to functionality. Starting with the following snippet, if the method variable output
is promoted, you end up with the second snippet:
Private Sub MethodA() MethodB() End Sub Private Sub MethodB() Dim output As String = "Test String" MessageBox.Show(output) End Sub
public void MethodA() { MethodB(); } public void MethodB() { string output = "Test String"; MessageBox.Show( output); }
After the variable is promoted, you can see that the initial value is now being passed through as a parameter wherever this method is referenced:
Private Sub MethodA() MethodB("Test String") End Sub Private Sub MethodB(ByVal output As String) MessageBox.Show(output) End Sub
public void MethodA() { MethodB("Test String"); } public void MethodB(string output) { MessageBox.Show( output); }
As you write code, you may realize that you need to call a method that you haven't written yet. For example, the following snippet illustrates a new method that you need to generate at some later stage:
Private Sub MethodA() Dim InputA As String Dim InputB As Double Dim OutputC As Integer = NewMethodIJustThoughtOf(InputA, InputB) End Sub
public void MethodA() { string InputA; double InputB; int OutputC = NewMethodIJustThoughtOf(InputA, InputB); }
Of course, the preceding code generates a build error because this method has not been defined. Using the Generate Method Stub refactoring action (available as a smart tag in the code itself), you can generate a method stub. As you can see from the following sample, the method stub is complete with input parameters and output type:
Private Function NewMethodIJustThoughtOf(ByVal InputA As String, ByVal InputB As Double) As Integer Throw New NotImplementedException End Function
private int NewMethodIJustThoughtOf(string InputA, double InputB) { throw new Exception("The method or operation is not implemented."); }
It's good practice to maintain a sorted list of Using statements in each file (in C#), and only reference those namespaces that are actually required within that file. The Organize Usings menu (available from the context menu when right-clicking in the code editor as shown in Figure 8-23) can help you in both these cases.
After a major refactoring of your code you may find that you have a number of using directives at the top of your code file that are no longer being used. Rather than going through a process of trial and error to determine what is and isn't being used, you can use an operation in Visual Studio to do this for you by right-clicking in the code editor and choosing Organize Usings
VB developers don't have a way to sort and remove unused Imports
statements. However, on the References tab on the Project Properties dialog, it's possible to mark namespaces to be imported into every code file. This can save significantly on the number of Imports
statements. On this page you also have the ability to remove unused assembly references.
It's good practice to organize the using directives in alphabetical order to make it easy to manage what namespaces are being referenced. To save you doing this manually you can right-click in the code editor and choose Organize Usings
To sort using directives and remove those that are not being used in one action, right-click in the code editor and choose Organize Usings
The default Visual Studio template code files have the using statements at the top of the file outside the namespace block. However, if you are following the StyleCop guidelines these specify that using statements should be contained within the namespace block. The Organize Usings functions handle either situation based upon the current location of the using statements in the file and retaining that location.
Code snippets are a valuable inclusion in the Visual Studio 2010 feature set. You learned in this chapter how to use them, and how to create your own, including variable substitution (and Imports
and reference associations for VB snippets). With this information you'll be able to create your own library of code snippets from functionality that you use frequently, saving you time in coding similar constructs later.
This chapter also provided examples of each of the refactoring actions available within Visual Studio 2010. Although VB developers do not get complete refactoring support out of the box, CodeRush Xpress provides a wide range of refactoring actions that enable them to easily refactor their projects.
3.17.76.72