Value Type hold actual value of data and stored in stack where reference type hold memory address of data and point to actual data and stack is used to store memory address of reference type and actual data stored into different memory that is heap.
So whenever we pass value of any value type data then the value is not changed whereas when we passing the reference type then as it is referenced to memory location of actual data then value get changed in caller method.
Generally value type are all numeric Data Types, Chars, Booleans, Enumerations and Structs whereas reference type are Classes, Strings, Arrays and Delegates.
Differences -
- Value types are stored on stack where Reference types are stored on heap.
- When passed as value type new memory location is created and stored the new value in this memory whereas in reference type it is pointing to same memory location and that's why passed value is get changed in memory.
- Value type holds actual data whereas Reference type hold memory address of the data and point to actual data.
- Value types cannot assign the value null whereas Reference types can be assigned the value null.
Example of Value type
int x=5;
int y=x;
It will create a two location of memory first with (x,5) and other one with (y,5).
Example of Reference Type
Employee e=new employee();
e.Id=101;
e.Name="Ramesh";
Employee e1=e;
e1.ID=102;
e1.Name="Rajesh";
Here e variable pointing to location of stored data on heap as (ID, Name) and when we assign e into new variable e1 then it is also pointing the same data (ID,Name).
Suppose if e has memory address 1000 and pointing to (ID,Name) of employee then e1 will also pointing the same memory address that is 1000 and will point to (ID,Name) .