Fundamentals as to what is the meaning of val type and ref type when passed by value and passed by reference.
Now as my site suggests "Dot Net Basics", so what I am posting is very basic stuff. So if you know these things already do not blame me for wasting your time later hahaha :-).
First thing first,
1) Value types sit on Stack.
2) Reference types sit on Managed heap. It is called Managed heap as it is managed by Garbage Collector.(Ref my earlier post for a better explanation on diff between value and ref type in terms of memory
GARBAGE COLLECTION ON VALUE AND REFERENCE TYPES).
Assignment Operators Behavior with Value and Reference Types
When one ValueType is assigned to another value type a new copy of the value type is created on the stack.
ex: Structure2 = Structure1;
When one reference type is assigned to another reference type, the reference of the new variable is redirected to point to the reference of the old reference type and no new copy is created. Basically both point to the same object on the heap.
Ex: Class 2= Class1;
Passing Reference and Value Types into Methods.
We all know we can pass parameters into methods in two ways, passByVal and passByRef, So this is how
ValueTypes and ReferenceTypes behavior differs, in both ways of passing the parameters.
Value Type Reference Type
PassedByValue A new copy is No new copy is created
created on stack. and only the state (data) of the
object can be changed
in the called method and
not the pointer, meaning
we cannot change what the
variable points to.
PassByRef No new copy is created Here u can change both the
on the stack, the same state of the object as well
copy is used. the variables reference,
meaning we can make the
variable to point to a new
object on the Heap.
One thing i will leave you to ponder on is, what happens when say My structure which holds a variable to a class, is assigned to another structure..whether a new copy of the class is created or not, as new copy of the structure is for sure created ?
Hope I was clear in making things understood, any comments and input are welcome and ofcourse appreciated.
Simple & Clear!
ReplyDeleteGood to see a post early in the month.And that reminds me .. I shd update my blog too :)
Good but old :P.. To answer ur question, no new class is created, a variable to a class would be an object which would lie on the heap. and assignnig that to another variable in another structure would just have two references to the class which would get updated when any of the two are changed :P
ReplyDelete