none
difference between dispose and setting an object to null RRS feed

  • Question

  • whats the difference between calling a dispose function versus setting the object to null?
    Monday, April 13, 2009 6:11 AM

Answers

  • You can't "set an object to null". You can set all references to an object to null (or change the references to another object), and that will result in the (eventual) garbage collection of the object. That may seem semantic, but it's a crucial point. It is necessary to understand the relationship between objects and references to them.

    The Dispose method is provided on objects that create external resources. If an object implements IDisposable, you should call Dispose to allow the object to release its external resources when you no longer need the object.

    A well designed object (which holds external resources) should release those resources in its finalizer (that is, when the object is garbage collected), but it's considered bad form to rely on the finalizer.
    Monday, April 13, 2009 2:30 PM

All replies

  • Hi sudeern,

    dispose method is used to cleanup unmanaged resources. Managed resources are cleaned up by Garbage collector automatically.

    Setting object to NULL, will not free up memory occupied by that object.


    -----------
    Adam Raheem
    • Proposed as answer by Raheem Abdur Monday, April 13, 2009 6:48 AM
    Monday, April 13, 2009 6:47 AM
  • i set  an object to null and in the memory footprint of the profiler , i dont see the object, by this it indicates that the object has been garbage collected right?

    Monday, April 13, 2009 6:56 AM
  • You can't "set an object to null". You can set all references to an object to null (or change the references to another object), and that will result in the (eventual) garbage collection of the object. That may seem semantic, but it's a crucial point. It is necessary to understand the relationship between objects and references to them.

    The Dispose method is provided on objects that create external resources. If an object implements IDisposable, you should call Dispose to allow the object to release its external resources when you no longer need the object.

    A well designed object (which holds external resources) should release those resources in its finalizer (that is, when the object is garbage collected), but it's considered bad form to rely on the finalizer.
    Monday, April 13, 2009 2:30 PM