It is shown by the name which variable store information or data directly that is a value type and which store a reference to information or data that is a reference type.
Let’s see a little more details: Value types are always stored on the stack and reference types address on the heap. In general int, enum, struct, etc. are simple examples of data type that store directly data are value type examples whereas reference type keep reference to data like class, interface, delegate, object, Arrays, etc.
In value type we can't store null value on the other hand reference type can have null. However, in value type, we can also achieve this by using nullable types.
Value type does not require garbage collectors they automatically popped/vanish when they go out of their scope whereas reference type requires garbage collectors to free up space.
Value types are assigned memory at compile time whereas in reference type memory assigned at run time.
Value Type:-
int amount = new int();
amount = 20;
int total = new int();
total = amount;
y = 30;
return amount;
--amount will return 20 because it has its location on the stack which is not affected so it keeps old value.
Reference Type:-
public class Student
{
public int Marks;
}
Student john = new Student();
john.Marks = 10;
Student mushi = new Student();
mushi = john;
mushi.Marks = 40;
Console.WriteLine(john.Marks);
--Output will be 40. Both student John and Mushi are referring to the same memory location on the heap.
No comments:
Post a Comment
Please do not enter spam links.