Visual Studio Macro – Identifier to String Literal

Posted by João Angelo on Exceptional Code See other posts from Exceptional Code or by João Angelo
Published on Sat, 11 Jun 2011 10:55:49 +0000 Indexed on 2011/06/20 16:37 UTC
Read the original article Hit count: 390

Filed under:
|

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 + """")
    Else
        Dim cursorPoint As EnvDTE.TextPoint

        cursorPoint = document.Selection.ActivePoint()

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

        editPointLeft = cursorPoint.CreateEditPoint()
        editPointLeft.WordLeft(1)

        editPointRight = editPointLeft.CreateEditPoint()
        editPointRight.WordRight(1)

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

© Exceptional Code or respective owner

Related posts about c#

Related posts about Visual Studio