2

I have an no named object created in a "with block".

With Factory.CreateSomeObject()
    .SomeProp = someValue
    ...
End With

My question is: how can I inspect the object when the debugger is in break mode?

Georg
  • 1,946
  • 26
  • 18
  • 2
    Interesting question and one that has presumably never come up for me as I've never considered it before. That seems It may not be possible and, if that's the case, the workaround would be to assign the result of the expression to a local variable and then use that variable in the `With` statement. – jmcilhinney Nov 15 '17 at 08:35
  • 2
    If you want to watch something, don't create it anonymously. I don't like the `With`-statement anyway. I've never understood it's benefits. The disadvantages clearly outweigh the advantages (if any). – Tim Schmelter Nov 15 '17 at 08:41
  • I think that's not a problem of code but of the debugger :) – Georg Nov 15 '17 at 08:51
  • 1
    As an addition to @TimSchmelter 's comment: https://stackoverflow.com/questions/283749/the-vb-net-with-statement-embrace-or-avoid – MatSnow Nov 15 '17 at 08:52
  • Thanks much @TimSchmelter, but I have to analyze the existing code only. I dont have the job to change them. – Georg Nov 15 '17 at 08:59
  • @Georg: at least you have good arguments why the code needs a review ;-) – Tim Schmelter Nov 15 '17 at 09:01

2 Answers2

2

I think this is not possible, but you can use an additional line:

Dim someObj As Object = Factory.CreateSomeObject()

With someObj
    .SomeProp = someValue
End With

With this solution you can inspect on the first line.

Some additional information on StackOverflow (similar question).

Sebastian Brosch
  • 42,106
  • 15
  • 72
  • 87
2

When I set a breakpoint on a line within a With block, The object returned from the function shows up in the Locals window. This is using VS2015. Further, if I right click on the function name on the With line and choose "Add Watch", the object is visible in the watch window.

My code:

Module Module1
    Sub Main()

        With FunctionThatCreatesAnA()
            Console.WriteLine("{0}, {1}", .SomeString, .SomeInteger)
        End With

        Console.ReadLine()
    End Sub

    Function FunctionThatCreatesAnA() As ClassA
        Return New ClassA With {.SomeString = "Blah Blah", .SomeInteger = 42}
    End Function
End Module

Public Class ClassA
    Public Property SomeString() As String
    Public Property SomeInteger() As Integer
End Class

Locals window:

enter image description here

Watch window:

enter image description here

Chris Dunaway
  • 10,974
  • 4
  • 36
  • 48
  • Thanks @Chris, it works great with the Locals window. But carefully with the second method: if you right click on the function name, you see another object as the created in the "with block". – Georg Nov 16 '17 at 08:41