Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Visual Studio suggest "TODO: set large fields to null."?

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.

like image 320
default.kramer Avatar asked Jul 30 '15 16:07

default.kramer


2 Answers

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.

like image 168
Hans Passant Avatar answered Oct 01 '22 16:10

Hans Passant


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.

like image 41
Jerry Federspiel Avatar answered Oct 01 '22 14:10

Jerry Federspiel