Visual Studio Macro – Identifier to String Literal

When implementing public methods with parameters it’s important to write boiler-plate code to do argument validation and throw exceptions when needed, ArgumentException and ArgumentNullException being the most recurrent.

Another thing that is important is to correctly specify the parameter causing the exception through the proper exception constructor.

In order to take advantage of IntelliSense completion in these scenarios I use a Visual Studio macro binded to a keyboard shortcut that converts the identifier at the cursor position to a string literal.

And here’s the macro:

Sub ConvertIdentifierToStringLiteral()
    Dim targetWord As String
    Dim document As EnvDTE.TextDocument

    document = CType(DTE.ActiveDocument.Object, EnvDTE.TextDocument)

    If document.Selection.Text.Length > 0 Then
        targetWord = document.Selection.Text
        document.Selection.ReplacePattern(targetWord, """" + targetWord + """")
        Dim cursorPoint As EnvDTE.TextPoint

        cursorPoint = document.Selection.ActivePoint()

        Dim editPointLeft As EnvDTE.EditPoint
        Dim editPointRight As EnvDTE.EditPoint

        editPointLeft = cursorPoint.CreateEditPoint()

        editPointRight = editPointLeft.CreateEditPoint()

        targetWord = editPointLeft.GetText(editPointRight)
        editPointLeft.ReplaceText(editPointRight, """" + targetWord + """", 0)
    End If
End Sub

2 thoughts on “Visual Studio Macro – Identifier to String Literal”

    1. Yes, but I haven’t yet had a chance to really experiment with code contracts. However, they are on my list of things to try.

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