KamalPatel.net
Back to Downloads/Articles

Convert Field To Property (Macro)

By Kamal Patel
May 16, 2002

Description
This is a very simple macro that adds the plumbing code to convert a declaration into a property.
If you have a delaration say:

Dim lcSelectedLine As String

The macro converts the above line into the following lines of code. Simply highlight the line you wish to convert and run the macro. 

'Dim lcSelectedLine As String

Private _lcSelectedLine As String

Public Property lcSelectedLine() As String

      Get

Return _lcSelectedLine

      End Get

Set(ByVal value As String)

_lcSelectedLine = value

End Set

End Property


Public Module CustomMacros

    Public Sub ConvertField2Property()

        'Get the currently selected line

        Dim lcSelectedLine As String

        Dim ts As TextSelection = DTE.ActiveDocument.Selection

        lcSelectedLine = ts.Text.Trim()

        'Declare and Initialize the tokens

        Dim lcRetVal, lcPropertyNameToken, lcPrefixToken, lcDataTypeToken As String

        lcPrefixToken = "_"  'Change this based on your requirements

        lcDataTypeToken = "String"  'Default

        lcPropertyNameToken = ""

        Try

            'Get the actual tokens

            'Assumes that only a single line will be selected

            'and the line will be of format

            'DIM MyVar As DataType

            'Declaration VariableName As DataType

            Dim laWords As String()

            laWords = lcSelectedLine.Split(" "c)

            lcPropertyNameToken = laWords(1)

            lcDataTypeToken = laWords(3)

            'Comment the current line and build the property

            lcRetVal = "'" + ts.Text + vbCrLf

 

            'Build the private variable here

            lcRetVal += vbTab + "Private " + lcPrefixToken + lcPropertyNameToken + " As " + lcDataTypeToken + vbCrLf

            'Build the property now

            lcRetVal += vbTab + "Public Property " + lcPropertyNameToken + "() As " + lcDataTypeToken + vbCrLf

            lcRetVal += vbTab + vbTab + "Get" + vbCrLf

            lcRetVal += vbTab + vbTab + vbTab + "Return " + lcPrefixToken + lcPropertyNameToken + vbCrLf

            lcRetVal += vbTab + "End Get" + vbCrLf

            lcRetVal += "        Set(ByVal value As " + lcDataTypeToken + ")" + vbCrLf

            lcRetVal += "            " + lcPrefixToken + lcPropertyNameToken + " = value" + vbCrLf

            lcRetVal += "        End Set" + vbCrLf

            lcRetVal += "   End Property" + vbCrLf

            ts.Insert(lcRetVal)

        Catch

            'Ignore the catch for now

        End Try

    End Sub

End Module