I’m working on a Silverlight app using the MVVM pattern. My ViewModel currently consists of a property that represents a collection of Model Objects:
public ObservableCollection<IndexEntry> IndexList { get; set; }
it also has several methods that will populate that collection with data that comes back from a webservice.
Since instances of this class may be created and destroyed over the course of the application runtime, should I implement IDisposable and set the property’s reference to null or will the destruction of this class be sufficient to remove all references to the collection tis property refers to? Are there any caveats that might leave a reference hanging out there?
Thanks.
The only way a reference survives garbage collection is if it is rooted. If there is some other class that is still in use that contains a reference to the ObservableCollection, then the ObservableCollection will not be destroyed, regardless of whether or not you set it to null. For example, suppose there is one ‘in memory’ object that is your collection. You have one reference to it, in your property. Some other code executes the line ‘ObservableCollection<> myOtherReference = YourObject.IndexList;’. They now have a reference to the actual memory object, too. Making your property reference null will only eliminate your property’s reference; the ‘myOtherReference’ reference is unaffected, as it is now pointing at the memory directly, and not at your property. If you really want to eliminate this item from memory, you need to remove ALL the references, or implement some decisive ‘dispose’ logic, at which point ‘myOtherReference’ would be a pointer to a disposed object, and any call to it will throw an exception.