다음을 통해 공유


Visual Studio Tip #4: Code Snippets

There is lots of code that we write that follow standard patterns with some minor changes for our exact situation. Visual Studio has a nice feature called Code Snippets which provides a way to create reusable code templates for common scenarios. The idea is that you activate the snippet, then just enter the needed values.

The ones I use the most are the snippets for .NET properties. There are actually two, one called “prop” and another called “propfull”. The code snippets are available from intellisense, so if I start typing “prop” inside my class and I can see the snippet

image

Then I select the snippet (hit Tab once to select the item in intellisense)

Then hit Tab again to activate the snippet. This is the result

image

 

A template of code is inserted and activated. Notice the two yellow rectangles? Those are the values I need to enter. Its like a little form for my code. In the image, the cursor is on the “int” one. If I press Tab again, it will select the next rectangle. In this way I can just type a new value in the rectangle, then press Tab to move to the next rectangle and enter the value there. So I just tab from one box to the next, changing values as needed and when I’m done, I press Enter and go back to regular code entry mode.

Try this: type “prop”, <Tab>, <Tab>, “string”, <Tab>, “Name”, <Enter>

You will end up with a simple property of type string named Name.

image

Now try the propfull snippet.

type “propfull”, <Tab>, <Tab>, “string”, <Tab>, “_city”, <Tab>, “City”, <Enter>

image

The propfull code snippet creates a full Property with a field to store the property’s value. Notice that when you entered “_city” that it changed in all 3 places in the code snippet.

Using these two code snippets you can very quickly fill out a new class’s properties.

There are lots of built in code snippets for lots of different things and you can also easily create your own (like I did for Windows 8 apps). To discover what's available, you can right click anywhere in your code and select “Insert Snippet” and you’ll get access to all the snippets by category. (If you work in XAML be sure to check out propdp and propa)

For more on Code Snippets see the documentation.

(next tip: quickly adding a namespace using statement)

This post is part of a series of Visual Studio tips. The first post in the series contains the whole list.