Macros in VS2010

Macros in Visual Studio are a really powerful feature – but hardly anyone I know uses them, or even knows about them. Perhaps that’s partly because they don’t get much coverage by the usual Microsoft bloggers etc. but I’ve been using them more and more lately as a really useful time saving device.

You can use macros any time that you’re doing some repetitive, boiler plate task. Visual Studio will record your key-presses and then play them back on demand. Small tasks work best since they are easiest to record, but there’s a whole scripting element to macros that let you create really powerful ones.

Here’s an example: –

class TestClass
    private string myString;
    private int someonesInt;
    private List<object> yourCollectionOfObjects;
    internal object someObject;
    private bool macrosAreCool;
    private DateTime todayIsTheFourthOfSeptember;

Let’s say that you wanted to make all these variables into public fields, and also correct the naming so that they were pascal cased. You could do this all yourself manually, or you could use a macro: –

  1. I get the cursor in place for the start of the “action” that I want to record – in this case, by the “p” in private
  2. I start recording the macro with CTRL + SHIFT + R
  3. I replace the word with “public ” (CTRL + SHIFT + RightCursor highlights the entire word)
  4. I use End to go to the end of the line, and then CTRL + LeftCursor twice to move to the start of the variable name
  5. SHIFT + RightCursor to highlight “m” in myString
  6. CTRL + SHIFT + U to make the “m” upper case
  7. DownCursor to go down to the next declaration line
  8. Home to go to the start of the line
  9. I stop recording with CTRL + SHIFT + R
  10. When I want to replay the macro, I hit CTRL + SHIFT + P

Obviously, they can do much more – imagine that you wanted to decorate all the fields in your class with e.g. serialization details like XmlElement() or DataContracts etc..

Or maybe you get some data sourced from on a webpage or text file and want to “codify” it e.g. you get a list of names (or whatever – some arbitrary data) to use within your application and want to make an enum out of it – with a well thought out macro this will take much less than doing it manually. In short – any repetitive task that can be automated.

As I said, there’s a whole scripting element to macros, and there are some examples bundled with VS – give it a go – it might be a real saver for you.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s