Value types and ref types in C#
value types and ref types are the types of data types classified on the basis of their allocation on stack and heap respectively.
value type variables directly contains the value which is assigned to them and these are stored on stack whereas reference type variables contain the reference of the data which they are assigned and the data is stored in the memory on heap.
All the basic data types in C# along with struct and enum are value types.
All value types are derived implicitly from System.ValueType
All value types are derived implicitly from System.ValueType
When we declare an integer in a program;
int X = 5;
memory for the variable is allocated on the stack and the variable is assigned with the initial value if given otherwise with the default value of that type.Every value type has an implicit default constructor which does this.
Now when we assign X to another variable,
int Y = X;
int Y = X;
memory for Y is created on the stack and value of X is assigned(copied) to Y.
Now consider when we declare a reference type variable (an object of a class)
MyClass obj1 = new MyClass();
Now consider when we declare a reference type variable (an object of a class)
MyClass obj1 = new MyClass();
memory for data which MyClass holds is allocated on the heap and only the reference of this data is stored in the variable obj1, which is stored on the stack.
When obj1 is assigned to another variable:
MyClass obj2 = obj1;
When obj1 is assigned to another variable:
MyClass obj2 = obj1;
Unlike value type variables here, the actual data is not again copied in the memory. Here obj2 also contains a reference to the data similar to oobj1.
Now when obj1 goes out of scope, the data still remains on the heap and only the reference of that data from obj1 is removed.
Now when obj1 goes out of scope, the data still remains on the heap and only the reference of that data from obj1 is removed.
Similarly if, obj2 also goes out of scope the reference of data from obj2 is also deleted but the data still remains in the memory. This data is now unreferenced block in the memory which is available for garbage collection. Garbage collector in C# automatically detects such unreferenced blocks in memory and frees the memory by deleting them unlike in C++ where we need to explicitly delete it.
0 comments: