How to refer to an object created using "c" inside a structure?

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

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

however, sometimes I would like to return an object:

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

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

+4
source share
3 answers

well, I think the answer is that while 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 
0
source

I would save the link to the instance before running the With block, and then Return after you have finished using the members:

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

You do not need to worry about the consequences of garbage collection, as the variable you create goes out of scope as soon as you return.

+2
source

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

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

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

If you do not need a variable, you can try the code as follows:

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

I do not believe that this syntax allows you to call methods on an instance. I think you can only set properties.

0
source

Source: https://habr.com/ru/post/1481008/


All Articles