Visual Studio Macro – Identifier to String Literal
- by João Angelo
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