The types are either treated by value type or by reference type.
Reference type variables are stored in the heap while value type variables are stored in the stack.
A value type holds the data within its own memory allocation and a reference type contains a pointer to another memory location that holds the real data.
Value Type:
When you created a value type, a single space in the 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 type can be created at compile time and stored in stack memory, because of this, garbage collector can't access the stack.
All the values are derived implicitly from the System.ValueType.
You cannot derive a new type from a value type. However, like reference types, structs can implement interfaces.
eg:- int X = 25;
Here the value 25 is stored in an area of memory called the stack.
When the variable X goes out of scopebecause the method in which it was defined has finished executing, the value is discarded from stack.
Using the stack is efficient, but the limited lifetime of value types makes them less suited for sharing data between different classes.
Each value type has an implicit default constructor that initialize the default value of that type.
Value type cannot contain the null value.
The nullable types features does allow for value types to be assigned to null.
Reference Type:
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 created a second copy of the reference, which refers to the same location of the heap as the original value.
When a reference type variable is no longer used, it can be reclaimed by garbage collector.
Reference type is created at run time.
eg: Classes, objects, arrays, indexers, interfaces, etc.
No comments:
Post a Comment