How to access the object itself in With … End With

There is no way to refer to the object referenced in the With statement, other than repeating the name of the object itself.

EDIT

If you really want to, you could modify your an object to return a reference to itself

Public Function Self() as TypeOfAnObject
    Return Me
End Get

Then you could use the following code

With Test.AnObject
    Test2.Subroutine(.Self())
End With

Finally, if you cannot modify the code for an object, you could (but not necessarily should) accomplish the same thing via an extension method. One generic solution is:

' Define in a Module
<Extension()>
Public Function Self(Of T)(target As T) As T
    Return target
End Function

called like so:

Test2.Subroutine(.Self())

or

With 1
   a = .Self() + 2 ' a now equals 3
End With

Leave a Comment