Hi Brian,
The example you gave was a private field beign set to nothing not a Shared Property. For a private field setting it to nothing has no impact unless you expect the containing class to stay around a lot longer. For example, consider this code:
Module Module1
Sub Main()
Dim a As New A
a.Open()
a = Nothing
Console.WriteLine("press enter to cause GC to collect")
Console.ReadLine()
GC.Collect()
Console.WriteLine("press enter to exit")
Console.ReadLine()
End Sub
End Module
Class A
Private _b As B = Nothing
Public Sub Open()
_b = New B
End Sub
Protected Overrides Sub Finalize()
Console.WriteLine("A finalized")
End Sub
End Class
Class B
Protected Overrides Sub Finalize()
Console.WriteLine("B finalized")
End Sub
End Class
You will see with the single call to Collect both Finalizers are called. So the GC collection catches all objects that are not referenced from a rootable object. When you think about it it has to do this to deal with circular references. The setting of the field to Nothing has no practical effect unless you are keeping the containing instance alive.
As to Shared properties, like I said previously you can't set them to nothing as then the behavior is no longer like they are shared and hence you shift the memory pressure to creating new instances. If containing types set their reference to Nothing a Shared property by nature will still be inmemory until the appdomain is unloaded.
This conversation details one of the reasons I dislike using Shared
properties. As I understand, the problem is that shared properties
aren't unreachable until the application ends, as at any time the
shared property could be referenced and the value would need to be
returned. The other problem is that you don't know (without making
dangerous assumptions about architecture and design) when a shared
property isn't going to be used anymore.
Consider the following:
///////////
Private Shared _MyDataSet As DataSet
Public Shared Property MyDataSet() As DataSet
Get
Return _MyDataSet
End Get
Set (value As DataSet)
_MyDataSet = value
End Set
End Property
///////////
Suppose at one part of the application, the MyDataSet is filled by a
query such as "Select * From tbl_BiggestTableInDatabase". For the rest
of the application's lifetime (this shared property won't go out of
scope) you have this massive dataset stored in memory. It would be
beneficial to set this to nothing and remove the dataset, but like I
said earlier, you can never be certain that you will know when the
property is not being used.
Thanks,
Seth Rowe [MVP]
http://sethrowe.blogspot.com/