Why set a Nothing object in a 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 it necessary to set o to Nothing

? What if I don't install it in Nothing

the block Finally

? I think it's ok if you don't set it to Nothing

, because the object will be marked for GC.

+3


source to share


2 answers


If the object is unsafe to use from a try catch, this should be done. If it were a stream, for example, you would see the stream closed and then nothing set. This is not always correct, but this code is very common.

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

      

Even though this is a silly example, it means that now you cannot refer to o outward because it is no longer bound to an object instance. This is why many people do it. If you are in a function and the function ends at this point, there is no need to set the value to Nothing because the object falls out of scope, however many people set stuff Nothing

out of habit . I would think that the wrong and bad code design

+4


source


This is because the object is not safe to use outside of the try .. catch .. finally block. He didn't guarantee it to be in a consistent state, so he set Nothing to make it obvious, not intended to be used.



0


source







All Articles