views:

121

answers:

5

I want to understand if code snippets are what I am looking for here.
I wind up writing the same line of code over and over during a refactoring.
Is there anyway I can create a shortcut that will spit out a line of code that I need?

A: 

Depending on the code snippet, it would almost always be arguable that this line of code belongs in a util method, rather than copypasta.. But otherwise, yeah - a snippet is probably the best place.

Chaos
A: 

Code Snippets sound like the right approach, although you could investigate Macros inside Visual Studio, which can be very powerful.

Scott Ferguson
+3  A: 
Jose Basilio
This is fine if the code is always the same, unless I am wrong. A code snippet allows you to define where the block of code may differ and flag them
phsr
A code snippet is always the best option. However this is a quick one-off solution.
Jose Basilio
+1  A: 

Are you repeating the same line of code over and over on many different days?

Or are you encountering a situation where you have the same line to write many times as a part of a single task, but today's line of code will be different to tomorrows?

If you have the same line/block of code that you use often, a snippet is a good way to capture that in a reusable form (better, IMHO, than copy/paste because you can parameterise them).

However, if you're just looking for a quick way to repeat the same line that's come up now, check out Visual Studio's ability to record keystrokes.

Try this:

  • Put your cursor on a blank line inside a C# method.
  • Select Tools|Macros|Record Temporary Macro (often this is Control-Shift-R)
  • Type "example();" and press return
  • Select Tools|Macros|Stop Recording

You've just created a temporary macro that you can play back at any time - usually the keystroke for this is Control-Shift-P.

The key to this technique is that the macro records everything you do - with some practise, you can record edits to a line of code and repeat those edits on other lines.

I've used this in the past to create repetative code blocks - like assigning sets of properties from one object to another.

Bevan
A: 

One advantage of a code snippet over adding it to the toolbox is that you can define the parts of the code that you want to change. I wrote a code snippet that generated something like the following code:

public class *className*Collection : List<*className*>

Where I only typed className once and it was automatically filled into the other parts.

phsr