Tuesday, August 31, 2010

Region-ify your C# code

There are some fancy tools/add-ons for Visual Studio that are huge productivity boosters. But for the poor man, purchasing an add-on is sometimes not an option.

Often, I review others' code (or perhaps my own code from a few years back), and think "What a newb! This junk is spaghetti code!". It is in situations like this where I find myself dying for the ability to collapse if blocks, while statements, etc. in C#.

As I mentioned there add ons that solve this quite eloquently. But, if you're just looking for a quick and dirty way to collapse those curly brackets, I have a macro for you! :)

In visual studio press the ALT key, followed by F8. This opens the macro pane. Most likely, there is already a macro project named my macros. Right click the module underneath that in the tree, and select "Edit". Now, blast this code into the editor:

'Add regions, by curly brackets. Put cursor on the first curly bracket of a pair, and run the macro.
Sub Regionify()
'region-ify
DTE.ActiveDocument.Selection.EndOfLine()
DTE.ActiveDocument.Selection.NewLine()
DTE.ActiveDocument.Selection.Text = "#region"
DTE.ActiveDocument.Selection.LineUp()
DTE.ExecuteCommand("Edit.GotoBrace")
DTE.ActiveDocument.Selection.LineUp()
DTE.ActiveDocument.Selection.EndOfLine()
DTE.ActiveDocument.Selection.NewLine()
DTE.ActiveDocument.Selection.Text = "#endregion"

'return to where I was
DTE.ActiveDocument.Selection.LineDown()
DTE.ExecuteCommand("Edit.GotoBrace")
End Sub

Another developer named Roland has a great post on how to assign hot keys to macros like this one. You can read about that here:

http://weblogs.asp.net/rweigelt/archive/2006/05/15/446536.aspx