oreilly.comSafari Books Online.Conferences.


AddThis Social Bookmark Button

Refactoring in Whidbey
Pages: 1, 2, 3, 4

Select the required language construct. In this case, the Try-Catch construct (see Figure 15).

Figure 15. Using a Try-Catch block

You should see the modified code as shown in Figure 16.

Figure 16. The modified code with the Try-Catch block

Insert Expansion

Another refactoring feature in C# is Insert Expansion. This is VB.NET's equivalent of the Code Snippet that I wrote some time ago (

Insert Expansion allows you to quickly add a block of pre-built code. This is a good way to insert code blocks without needing to remember its exact syntax. To insert a code expansion, position the cursor and right-click. Select Refactor -> Insert Expansion... (see Figure 17).

Figure 17. Inserting a code expansion

You can then select the expansion snippet you want (see Figure 18).

Figure 18. Selecting the expansion snippet

Once the code snippet is inserted, you can customize the code by filling in the yellow boxes (see Figure 19).

Figure 19. Customize your code by changing the code in yellow

Just as in VB.NET, you can write your own custom expansion snippet. The snippets are XML files located in C:\Program Files\Microsoft Visual Studio 8\VC#\Expansions\1033\Expansions.

An expansion snippet looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippet Format="1.0.0">
        <Title>if statement</Title>
        <Description>Expansion snippet for if Statement</Description>
            <Literal default="true">
                <ToolTip>Expression to evalute</ToolTip>
        <Code Language="csharp" Format="CData"><![CDATA[if ($expression$)
      $selected$ $end$

Generate Method Stub

Another refactoring feature that is not listed when you perform a right-click is Generate Method Stub. You can see this feature when you click on the Refactor menu. This feature is useful when you want to call a function that has not been written yet. For example, I may have a function named getResult() that returns a string type. So I have:

private void Form1_Load(object sender, EventArgs e) {
	string result = getResult();

Position your cursor on the getResult() function and click on the Refactor -> Generate Method Stub menu item (see Figure 20).

Figure 20. Generating a method stub

It will automatically generate a method stub containing a Throw statement:

private string getResult()
  throw new NotImplementedException();

You can simply modify this stub for your use.


Code refactoring is one of new features in Visual Studio .NET 2005. It will certainly make the life of the C# developer much easier. Once again, Microsoft has made significant progress in the IDE, making .NET a very compelling framework for developing Windows applications.

Wei-Meng Lee (Microsoft MVP) is a technologist and founder of Developer Learning Solutions, a technology company specializing in hands-on training on the latest Microsoft technologies.

Return to