ekkis
ekkis

Reputation: 10226

How to refer to an object created by "with" within the construct?

I often use with to create an object and run its methods. it makes the code look clean:

With New MyObj(...)
  .Prop1 = Val1
  .Prop2 = Val2
  .Run()
End With

however, sometimes I'd like to return the object:

With New MyObj(...)
  .Prop1 = Val1
  .Prop2 = Val2
  Return .Me
End With

but not all objects have a Me (this) property, so how can I refer to the object in question within the with?

Upvotes: 5

Views: 447

Answers (3)

Chris Dunaway
Chris Dunaway

Reputation: 11216

You can use the VB object initializer syntax with Option Infer:

Dim variable As New SomeClass With
{
    .AString = "Hello",
    .AnInteger = 12345
}
return variable

You still have a variable, but it's pretty clean.

If you don't want the variable you might try code like this:

Return New SomeClass With
{
    .AString = "Hello",
    .AnInteger = 12345
}

I don't believe this syntax allows you to call methods on the instance, however. I think you can only set properties.

Upvotes: 0

ekkis
ekkis

Reputation: 10226

well, I guess the answer is that so long as I can change the definition of the object in question I can do this:

Public Class XC
    Public Self As XC = Me
End Class

With New XC()
  Dim x As XC = .Self
End With

Upvotes: 0

user1726343
user1726343

Reputation:

I would retain a reference to the instance before starting the With block, then Return it after you're done using the members:

Dim myInstance = New MyObj(...)
With myInstance
  .Prop1 = Val1
  .Prop2 = Val2
End With
Return myInstance

You don't need to worry about garbage collection implications, since the variable you are creating goes out of scope once you return anyway.

Upvotes: 2

Related Questions