B
Brian Gideon
Yes, I call Close if it is available, Dispose if it is available and thenset the object to nothing
before it goes out of scope. As I see it, the only open item is whether or not to force garbage
collection.
There's no reason to set a reference variable to Nothing before it
goes out of scope. The object referenced by that variable will be
collected in the exact same manner whether or not the variable is set
to Nothing. In fact, what most people don't realize is that objects
referenced by local variables are actually eligible for collection
*before* the variable goes out of scope (assuming of course there are
no other references).
Consider this example.
Public Sub DoSomething()
Dim a As Object = New Object()
Dim b As Object = New Object()
PretendToUseObject(a)
PretendToUseObject(b)
b = Nothing
End Sub
Public Sub PretendToUseObject(ByVal x As Object)
Console.WriteLine("I'm not doing anything with x.")
End Sub
The conventional wisdom is that the objects referenced by 'a' and 'b'
are eligible once DoSomething exits. But, that's not the case. In
reality, the object referenced by 'a' is eligible immediately after
the first call to PretendToUseObject is invoked and even before
PretendToUseObject even completes. The reason is because the GC is
smart enough to know that 'a' is never used after being passed as a
parameter to another method. Now, using that logic we applied to 'a'
you can see that 'b' is eligible before it is assigned to Nothing.