When writing VB.NET in Visual Studio (2010 at least), if you create a class that implements IDisposable
the IDE will generate this skeleton for you:
' IDisposable
Protected Overridable Sub Dispose(disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
' TODO: dispose managed state (managed objects).
End If
' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
' TODO: set large fields to null.
End If
Me.disposedValue = True
End Sub
If I understand garbage collection correctly, setting fields to null would serve no purpose.* But why would Visual Studio recommend it then?
*Assuming that you aren't holding live references to the object that is being disposed, which would be strange.
There is in general very little to admire about this auto-generated code. The disposable pattern has been obsolete for the past 10 years, elegantly replaced by critical finalizers in .NET 2.0. But not completely gone, several handfuls of .NET classes from the 1.0 days implement it. And when you derive from such a class then you're stuck with having override the Dispose(Boolean)
method. Sadly the VB.NET editor isn't smart enough to detect this corner-case.
Best way to categorize the advice is to not label it as correct but as "not wrong". As long as a VB.NET programmer blindly follows the advice they'll never get in trouble. Nothing wrong with that.
The "set large fields to null" advice also thoroughly falls in the "not wrong" category. It will not often make any difference, it is however technically possible that the "large object" lives in an earlier GC generation. Which is somewhat likely to happen when it was allocated late, long after the disposable object was created. Setting it to Nothing
then allows the GC to release it earlier and the program will run leaner. Nothing wrong with that.
Someone might hold a reference to the object being Disposed
for any amount of time. But as the implementer of the IDisposable
class, you know that you don't need the large object after Dispose()
. To allow the large object to be collected as soon as possible, set it to null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With