Search code examples
.netdebuggingdisposelocals

.Net: When you dispose() variable, should it immediately, visibly be set to "Nothing" in debugger Locals window?


When you dispose() a variable, should it immediately, visibly be set to "Nothing" in debugger Locals window?

When I single step this in the Visual Studio 2010 debugger, I can see in the Locals window that the close() call does set r1's BaseStream and various other members to Nothing, but the dispose() call does NOT set the r1 variable as a whole to "Nothing". It's still listed in the Locals window as {System.IO.StreamReader}.

Try
     r1 = New System.IO.StreamReader("c:\temp\dummy\dummy1.txt")
Finally
    If Not IsNothing(r1) Then
        r1.Close()
        r1.Dispose()
    End If
End Try

Maybe my expectations are just mismatched with how it actually works. Is there a definitive reference to explain this behavior?

EDIT: Yes, I was already aware of the Using statement, but I need to allocate two db connections, and two db commands (one for each of the opened connections). Nesting using statements four-deep seemed convoluted. Furthermore I wanted to implement a three-strikes-and-you're-out while-loop around each of the New Connection() statements, because they are prone to fail in my current environment and I'm specifically trying to troubleshoot that. If someone can point me to a useful structure for blending Whiles and Usings, they get a gold star for the day.


Solution

  • Dispose is a method like any other and it does not set the variable to Nothing (or null in C#)

    The purpose of the Dispose method is to "[perform] application-defined tasks associated with freeing, releasing, or resetting unmanaged resources." (source)

    Because of that, an object is often unusable after it has been disposed but the variable it is assigned to remains unchanged until you reassign it yourself explicitely.

    With that being said, you should generally use a using statement for disposable objects.

    Using r1 As New System.IO.StreamReader("c:\temp\dummy\dummy1.txt")
       'Code goes here
    End Using