Sunday, May 1, 2011

How can I keep from retyping the same line of code over and over?

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?

From stackoverflow
  • 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.

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

  • Another easier option is to drag the code blocks that you re-use frequently onto the general tab of your toolbox area. You could even organize them with their own tab name and all.

    alt text

    phsr : 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
    Jose Basilio : A code snippet is always the best option. However this is a quick one-off solution.
  • 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.

  • 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.

0 comments:

Post a Comment