Vb.net – How to access the object itself in With … End With


Some code to illustrate my question:

With Test.AnObject

    .Something = 1337
    .AnotherThing = "Hello"

    ''// why can't I do this to pass the object itself:
    ''// ... and is there an equivalent, other than repeating the object in With?

End With

Best Solution

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


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
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
Public Function Self(Of T)(target As T) As T
    Return target
End Function

called like so:



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