Code Snippets: Using Code Snippets and “Surround With…”

Code Snippets, a phrase that is similar to “templates”.  You might be reading an article that says: “I have included code snippets for you to use”, and when you look at the attached file it is just a bunch of code, useful but not technically code snippets.  This is similar to when you get a “template” from your co-worker and it turns out to be a Word Document and not a file with the extension .DOTX.

What is a code snippet and how to you make one?  In Visual Studio, if you type the word “for” and then hit tab twice you get the following:

Code Snippet

  1. for (int i = 0; i < length; i++)
  2. {
  3.     
  4. }

You get the first line as well as the two braces.  Cool.

Let’s say you have a few lines of code (I show a single line of code for brevity):

Code Snippet

  1. sillybilly = beepbeep;

And you want to place the line inside of a for loop, or other statement, first select the line or lines of code right click next to the line or lines of code and select “surround with” then select the state you want to do the surround with:

image

Once you select the Surround With, and this is something you want to memorize the keystrokes to use in the future, you will see a list and in the case I will select the “for” loop:

image

Now the code looks like:

Code Snippet

  1. for (int i = 0; i < length; i++)
  2. {
  3.     sillybilly = beepbeep;
  4. }

As you can see you have saved a number of keystrokes, naturally you have to go into the code and make the appropriate changes, but it gets the correct format.

Conclusion:

  1. Use code snippets to save time and be more efficient, it might seem like you are being more efficient by not using code snippets, but you do save time and maintain a higher level of quality while saving time.
  2. Using the “Surround With…” Can help with getting the braces correct and some of the other formatting issues done correctly