Saturday, August 4, 2012

Visual Studio Tips and Tricks, Part I: Surround With

Visual Studio software products are a common and fundamental tool for most ASP.NET developers (and can also be used by developers and web designers for many environments). The following 3-part series illustrates a few quick tips and tricks that may help you with your work using these applications. These features are available in various versions of the Visual Studio family, including Visual Web Developer and Visual C# Express.




In this series, we'll look at the following quick-use features to speed up your code work:
  • Surround With
  • Format Document/Selection
  • Collapsible sections (and the #region)

Surround With

A common coding conundrum is the need to "wrap" some tag or code block around another section of code. The manual approach to this would be to type the opening tag or code block before the section to be surrounded; then scroll down to the end of that section and type the closing tag or code block afterwards.

A shortcut for these steps is to use the Surround With feature of Visual Studio:
  1. Select the code to surround with some other common tag or code block (such as an HTML div or a C# if block).
  2. Right-click on the selection and choose "Surround With…"
    • Alternative methods:
      • Menu system Edit menu, IntelliSense submenu, Surround With…
      • Shortcut keys CTRL+K, then release and CTRL+S
  3. Below the selected code, a pop-up menu will either display folders for different types of snippets (double-click the folder to enter), or it will display allowable snippets for that context.
  4. Double-click the desired tag or code block to surround the selected area.

Code before Surround With
In this example, the C# code should only be run if the number2 variable does not equal zero. It's a prime candidate to Surround With a C# if statement.


Applying Surround With to code, step 1
The C# code after it's been selected and right-clicked for the Surround With feature.


Applying Surround With to code, step 2
After selecting Surround With, the pop-up menu offers various snippets for surrounding the code.


Code after applying Surround With for an IF statement
The C# code after using Surround With to wrap the if statement around the code, and updating the statement's condition to only run when the number2 variable doesn't equal 0.

In the case of adding a standard if block for C#, be sure to choose the 2nd if listed (not the first one preceded by the # sign).

No comments:

Post a Comment