Hi,
What is the difference between null and disposed object in the memory?
Thanks,
Popskie
Printable View
Hi,
What is the difference between null and disposed object in the memory?
Thanks,
Popskie
A variable is a memory location on the stack. If that memory location contains all zeroes then it is null, i.e. it refers to no object.
A reference type object is stored on the heap. Once the system creates an object it exists until the system reclaims the memory it occupies. An object can still exist and be disposed. Disposing an object means releasing its unmanaged resources. For instance, a Form has a window handle. When you dispose a Form you release its window handle back to the system. The Form object still exists but it has no window handle so it cannot be displayed. You can still acess its members though because it still exists in memory.If the variable had been set to null before calling the Form's Dispose method then the object would still be eligible for garbage collection but when the garbage collector came to clean it up it would have to dispose it first by invoking its Finalize method. Actually reclaiming the memory it occupies would have to wait for the next pass of the garbage collector. That's why not disposing objects makes your app less efficient: it holds onto both unmanaged resources and memory longer than it needs to.Code:Form f;
// The preceding code creates a variable on the stack.
// The memory location is full of zeroes so the variable is null.
f = new Form();
// The preceding code creates a Form object on the heap and assigns its address to the 'f' variable.
// The variable no longer contains zero so it is no longer null.
// It now refers to an object, i.e. contains the memory address of an object.
f.Dispose();
// The preceding code disposed the Form that the 'f' variable referred to.
// The variable is still not null because it still refers to an object.
// The Form object still exists but it has no window handle so it cannot be displayed.
f = null;
// The preceding code specifically sets the 'f' variable to null, i.e. fills it with zeroes.
// The variable no longer refers to the Form object because it no longer contains its memory address.
// The form is no longer referred to by any variables so it is now eligible for garbage collection.
ok jm , Its nice input.