Reputation: 10226
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
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
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
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