vb.netobjecttry-catch-finally

Why to set an object to Nothing in the Finally block?


In this VB.NET code:

Dim o as SomeClass
Try
   o = new SomeClass
   'call some method on o here
Catch(...)
   ...
Finally
   o = Nothing
End Try

Why is there a need to set o to Nothing? What if i don't set it to Nothing in the Finally block? What i think is that it is OK if you don't set it to Nothing because the object will be marked for GC.


Solution

  • If the object is unsafe to use out of the try catch should this be done. If this was a stream for example you'd see the stream closed and then set to nothing. It is not always the right thing to do but this code is seen a lot.

    consider this code

    Sub Main()
        Dim o As String
        Try
            o = "Hello"
            Console.Out.WriteLine("hi {0}", o)
        Catch ex As Exception
            ' do something here
        Finally
            o = Nothing
        End Try
    
        ' unable to do something here
    End Sub
    

    Allthough it is a silly example it does mean you cannot reference o outside now because it is no longer set to an instance of an object. That is why it is done by a lot of people. If you are in a function and a function ends at that point there is no need to set to Nothing as the object falls out of scope however lots of people will set stuff to Nothing out of habit I'd consider that incorrect and bad code design