There's one major gripe I have with the VB language.. the With/End With block. Although it shortens code lines when setting lots of properties I find it harder to read, error prone when moving code around, and very awkward to debug since you can't just select the property and add a watch.
I never use this syntax in my own code, always preferring to have everything in long form, it doesn't increase typing too much with intellisense and we all have fairly large displays these days so line length is less of an issue as well.
So when using code I find on the net or from colleagues the first thing I do is remove with blocks. Getting fed up with this time consuming but quite dumb task I've created a Visual Studio macro to do it.
As an example, code with a With statement like the following;
Public Sub AWithExample()
With Me
.Text = "Hello"
.Tag = "This"
MessageBox.Show(.Text, "Title " & .Text)
Dim x As String
x = .Text
End With
End Sub
Becomes;
Public Sub AWithExample()
Me.Text = "Hello"
Me.Tag = "This"
MessageBox.Show(Me.Text, "Title " & Me.Text)
Dim x As String
x = Me.Text
End Sub
The Macro's quite trivial, just create a new macro and add the following code;
Imports SystemImports EnvDTEImports EnvDTE80Imports System.DiagnosticsPublic Module UnWith Public Sub UnWith() 'Removes With statements from vb code. 'To use, run this macro from within a with statement block Dim ts As TextSelection = DTE.ActiveWindow.Selection 'Step backwards from current point and find the line beginning with With Dim foundWith As Boolean = False Do ts.SelectLine() If ts.Text.Trim.StartsWith("With") Then foundWith = True Else ts.LineUp() If ts.ActivePoint.AtStartOfDocument = True Then Exit Do End If End If Loop Until foundWith = True 'If found the With statement get the object name and delete the With line If foundWith Then If ts.Text.Trim.StartsWith("With") Then Dim withObjName As String withObjName = ts.Text.Trim.Remove(0, 5) ts.Delete() 'Start searching down for " ." elements and replacing with obj. instead 'Until a line starting with End With found Do ts.SelectLine() If Not ts.Text.Trim.StartsWith("'") Then 'If not a comment try a replace ts.ReplacePattern(" .", " " & withObjName & ".") ts.ReplacePattern("(.", "(" & withObjName & ".") End If Loop Until ts.Text.Trim.StartsWith("End With") 'Remove the End With line If ts.Text.Trim.StartsWith("End With") Then ts.Delete() End If End If 'Remove the indenting of the former with statements DTE.ExecuteCommand("Edit.FormatDocument") Else System.Windows.Forms.MessageBox.Show( _
"No With statement detected.", "UnWith", _ System.Windows.Forms.MessageBoxButtons.OK, _
System.Windows.Forms.MessageBoxIcon.Exclamation) End If End SubEnd Module