What is the difference between a reference type and value type in c#?

Value type:

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:

  1. When large set of values are passed to a method the receiving variable actually copies so there are two redundant values in memory.

  2. As classes are missed out.it losses all the oop benifits

Reference type:

Holds a memory address of a value not value

Example:

Class

Storage:

Stored on heap

Advantages:

  1. 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.

  2. When the size of variable is bigger reference type is good

  3. 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


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:

  1. allocate memory (say starting at memory location 1000 for 5 bytes) and put H (at 1000), e (at 1001), l (at 1002), l (at 1003) and o (at 1004).
  2. allocate somewhere in memory (say at location 0500) and assigned it as the variable a.
    So it's kind of like an alias (0500 is a).
  3. assign the value at that memory location (0500) to 1000 (which is where the string Hello start in memory). Thus the variable a is holding a reference to the actual starting memory location of the "Hello" string.

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:

  1. allocate a memory location say at 0500 and assign it to variable a (the same alias thing)
  2. put the value 1 in it (at memory location 0500).
    Notice that we are not allocating extra memory to hold the actual value (1). Thus a is actually holding the actual value and that's why it's called value type.

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:

  1. Created 2 spaces in memory sufficient to hold 32 bit integer values.
  2. Placed a value of 3 in the memory allocation assigned to A
  3. Placed a value of 3 in the memory allocation assigned to B by assigning it the same value as the held in A.

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 . . .


Your examples are a little odd because while int, bool and float are specific types, interfaces and delegates are kinds of type - just like struct and enum are kinds of value types.

I've written an explanation of reference types and value types in this article. I'd be happy to expand on any bits which you find confusing.

The "TL;DR" version is to think of what the value of a variable/expression of a particular type is. For a value type, the value is the information itself. For a reference type, the value is a reference which may be null or may be a way of navigating to an object containing the information.

For example, think of a variable as like a piece of paper. It could have the value "5" or "false" written on it, but it couldn't have my house... it would have to have directions to my house. Those directions are the equivalent of a reference. In particular, two people could have different pieces of paper containing the same directions to my house - and if one person followed those directions and painted my house red, then the second person would see that change too. If they both just had separate pictures of my house on the paper, then one person colouring their paper wouldn't change the other person's paper at all.