Sunday, October 21, 2007

Value type and reference type differences

I have been reading a lot about the differences between value type and reference type elsewhere in the internet. The concept is simple if tried to understand the memory allocation for these two in the memory. A value type is allocated in a stack (first in last out fashion). A reference type object is allocated in a heap and a reference object to this space in the heap is allocated in the stack.

Then interesting thing is that once this reference to the heap goes out of scope how does the stuff in heap get cleaned. This is where the garbage collector comes into action. I read a nice article on albahari's (http://www.albahari.com/value%20vs%20reference%20types.html) web site that tells us how to get these space de-alllocated automatically from the heap.

If an object can be added to a container that is aware about its job to clean or destroy all its children then we do not need an exclusive call to the dispose method of the object itself.

For example if we create a text box, we need to first add it to the container control. Now when the form itself gets destroyed, it will automatically remove the textbox details from the heap!.

This means that if we create a text box like in the following statment

TextBox myText= new TextBox();
myForm.Controls.Add(myText);
myText = null;

In the above code the text box does not get destroy even though we have assigned null value to myText reference object. The GB will detect that the textbox in the heap is being referenced by the Form! (myForm.Controls.Add())

No comments: