Description:recently I have gone through an interview where I have been asked why a software developer should know about the difference between value type and reference type, by definition I know both terms but what are the condition where I have to choose any one of them and the other couldn't do the same thing for me ?
Posted by: Samantha Jones | Posted on: Feb 08, 2019
A value type derives from System.ValueType and stores its contents in memory allocated on the stack. When you created a Value Type, a single space in memory is allocated to store the value and that variable directly holds a value. If you assign it to another variable, the value is copied directly and both variables work independently. Value types can be created at compile time and Stored in stack memory, because of this, Garbage collector can't access the stack.
Some Value Types are:
A reference type extends System.Object and used by a reference which holds a reference (address) to the object but not the object itself. Because reference types represent the address of the variable rather than the data itself, assigning a reference variable to another doesn't copy the data. Instead it creates a second copy of the reference, which refers to the same location of the heap as the original value. Reference Type variables are stored in a different area of memory called the heap. This means that when a reference type variable is no longer used, it can be marked for garbage collection.
Some Reference Types are:
-All arrays, even if their elements are value types
Now for further explanation I have created a simple console application which will help you understand the difference in terms of usage.
Above code’s output will be as follows:
ValueType Inside the method=110;
Now to get more clarity regarding the above code and its output, what happens here(for value type) is that value type created the copy of the variable with actual data which will work independently, when we have incremented the value inside the method that incremented value has the scope inside the method only. So when we have printed the value inside the method it has been printed as incremented value (110) and when we have printed it outside the method it actually printed the original variable’s value which was 100.
While on the other hand reference type created the copy of the variable which holds the address of another memory location containing the actual data so both copies points to the same data, So when we have incremented the value it actually incremented the value which is shared among both variable (the original one and the copy) and now when we have printed the value for reference type it displayed the incremented value as 110.
Replied by: Tabish Usman | Replied on: Feb 11, 2019