Search code examples
c#dispose

To dispose an object should I set all properties to null?


I am currently trying to implement my first dispose on some of my objects, and was wondering if its a bad idea to go through all the properties per reflection and just set them to null?


Solution

  • Implementing IDisposable doesn't mean that you've to set all the fields to null. GC will take care of that when they are not reachable from the root objects.

    And setting null will not do anything still the object will be in memory till GC notices it is not having managed any references.

    IMO you can't see a comprehensive answer more than this Proper use of the IDisposable interface

    Setting null helps only when there is only one managed reference left, you don't need it though but you need to keep the encapsulating type alive then you'll set reference to null. Otherwise if encapsulating type itself is not reachable then setting null doesn't makes any sense.