Some guy asked me this question couple of months ago and I couldn\'t explain it in detail. What is the difference between a reference type and a value type in C#?
I
I found it easier to understand the difference of the two if you know how computer allocate stuffs in memory and know what a pointer is.
Reference is usually associated with a pointer. Meaning the memory address where your variable reside is actually holding another memory address of the actual object in a different memory location.
The example I am about to give is grossly over simplified, so take it with a grain of salt.
Imagine computer memory is a bunch of PO boxes in a row (starting w/ PO Box 0001 to PO Box n) that can hold something inside it. If PO boxes doesn't do it for you, try a hashtable or dictionary or an array or something similar.
Thus, when you do something like:
var a = "Hello";
the computer will do the following:
Value type will hold the actual thing in its memory location.
Thus, when you do something like:
var a = 1;
the computer will do the following:
Holds some value not memory addresses
Example:
Struct
Storage:
TL;DR: A variable's value is stored wherever it is decleared. Local variables live on the stack for example, but when declared inside a class as a member it lives on the heap tightly coupled with the class it is declared in.
Longer: Thus value types are stored wherever they are declared.
E.g.: an int
's value inside a function as a local variable would be stored on the stack, whilst an in int
's value declared as member in a class would be stored on the heap with the class it is declared in. A value type on a class has a lifetype that is exactly the same as the class it is declared in, requiring almost no work by the garbage collector. It's more complicated though, i'd refer to @JonSkeet's book "C# In Depth" or his article "Memory in .NET" for a more concise explenation.
Advantages:
A value type does not need extra garbage collection. It gets garbage collected together with the instance it lives in. Local variables in methods get cleaned up upon method leave.
Drawbacks:
When large set of values are passed to a method the receiving variable actually copies so there are two redundant values in memory.
As classes are missed out.it losses all the oop benifits
Holds a memory address of a value not value
Example:
Class
Storage:
Stored on heap
Advantages:
When you pass a reference variable to a method and it changes it indeed changes the original value whereas in value types a copy of the given variable is taken and that's value is changed.
When the size of variable is bigger reference type is good
As classes come as a reference type variables, they give reusability, thus benefitting Object-oriented programming
Drawbacks:
More work referencing when allocating and dereferences when reading the value.extra overload for garbage collector
Value Type:
Fixed memory size.
Stored in Stack memory.
Holds actual value.
Ex. int, char, bool, etc...
Reference Type:
Not fixed memory.
Stored in Heap memory.
Holds memory address of actual value.
Ex. string, array, class, etc...
This is from a post of mine from a different forum, about two years ago. While the language is vb.net (as opposed to C#), the Value Type vs. Reference type concepts are uniform throughout .net, and the examples still hold.
It is also important to remember that within .net, ALL types technically derive from the base type Object. The value types are designed to behave as such, but in the end they also inherit the functionality of base type Object.
A. Value Types are just that- they represent a distinct area in memory where a discrete VALUE is stored. Value types are of fixed memory size and are stored in the stack, which is a collection of addresses of fixed size.
When you make a statement like such:
Dim A as Integer
DIm B as Integer
A = 3
B = A
You have done the following:
The Value of each variable exists discretely in each memory location.
B. Reference Types can be of various sizes. Therefore, they can't be stored in the "Stack" (remember, the stack is a collection of memory allocations of fixed size?). They are stored in the "Managed Heap". Pointers (or "references") to each item on the managed heap are maintained in the stack (Like an Address). Your code uses these pointers in the stack to access objects stored in the managed heap. So when your code uses a reference variable, it is actually using a pointer (or "address" to an memory location in the managed heap).
Say you have created a Class named clsPerson, with a string Property Person.Name
In this case, when you make a statement such as this:
Dim p1 As clsPerson
p1 = New clsPerson
p1.Name = "Jim Morrison"
Dim p2 As Person
p2 = p1
In the case above, the p1.Name Property will Return "Jim Morrison", as you would expect. The p2.Name property will ALSO return "Jim Morrison", as you would Iintuitively expect. I believe that both p1 and p2 represent distinct addresses on the Stack. However, now that you have assigned p2 the value of p1, both p1 and p2 point to the SAME LOCATION on the managed heap.
Now COnsider THIS situation:
Dim p1 As clsPerson
Dim p2 As clsPerson
p1 = New clsPerson
p1.Name = "Jim Morrison"
p2 = p1
p2.Name = "Janis Joplin"
In this situation, You have created one new instance of the person Class on the Managed Heap with a pointer p1 on the Stack which references the object, and assigned the Name Property of the object instance a value of "Jim Morrison" again. Next, you created another pointer p2 in the Stack, and pointed it at the same address on the managed heap as that referenced by p1 (when you made the assignement p2 = p1).
Here comes the twist. When you the Assign the Name property of p2 the value "Janis Joplin" you are changing the Name property for the object REFERENCED by Both p1 and p2, such that, if you ran the following code:
MsgBox(P1.Name)
'Will return "Janis Joplin"
MsgBox(p2.Name)
'will ALSO return "Janis Joplin"Because both variables (Pointers on the Stack) reference the SAME OBJECT in memory (an Address on the Managed Heap).
Did that make sense?
Last. If you do THIS:
DIm p1 As New clsPerson
Dim p2 As New clsPerson
p1.Name = "Jim Morrison"
p2.Name = "Janis Joplin"
You now have two distinct Person Objects. However, the minute you do THIS again:
p2 = p1
You have now pointed both back to "Jim Morrison". (I am not exactly sure what happened to the Object on the Heap referenced by p2 . . . I THINK it has now gone out of scope. This is one of those areas where hopefullly someone can set me straight . . .). -EDIT: I BELIEVE this is why you would Set p2 = Nothing OR p2 = New clsPerson before making the new assignment.
Once again, if you now do THIS:
p2.Name = "Jimi Hendrix"
MsgBox(p1.Name)
MsgBox(p2.Name)
Both msgBoxes will now return "Jimi Hendrix"
This can be pretty confusing for a bit, and I will say one last time, I may have some of the details wrong.
Good Luck, and hopefully others who know better than me will come along to help clarify some of this . . .
Variable types and Reference Value are easy to apply and well applied to the domain model, facilitate the development process.
To remove any myth around the amount of "value type", I will comment on how this is handled on the platform. NET, specifically in C # (CSharp) when called APIS and send parameters by value, by reference, in our methods, and functions and how to make the correct treatment of the passages of these values.
Read this article Variable Type Value and Reference in C #
Suppose v
is a value-type expression/variable, and r
is a reference-type expression/variable
x = v
update(v) //x will not change value. x stores the old value of v
x = r
update(r) //x now refers to the updated r. x only stored a link to r,
//and r can change but the link to it doesn't .
So, a value-type variable stores the actual value (5, or "h"). A reference-type varaible only stores a link to a metaphorical box where the value is.