Value
Types
|
Reference
Types
|
Value
types are allocated in stack |
Reference
types are allocated in heap |
Value
type directly contain the data |
Reference
type doesn't hold the data directly, instead they hold the memory
address in which the data is stored |
When
you specify int num1 = num2, then the data in value type variable
num2 is copied into num1. However, num1 and num2 have individual copies
of data |
When
you specify sampleClass obj2 = obj1, then both obj2 and obj1 are pointing
to the same reference i.e. to the same memory location |
System.ValueType
is the base class of all value types. However System.ValueType is
derived from System.Object |
All
reference types are directly inherited from System.Object |
To convert
a value type to an Object and vice versa, you have to perform boxing
and unboxing |
Reference
types can directly be assigned to an Object and vice versa. It doesn't
require boxing or unboxing to happen |
Value
types cannot accept null values unless otherwise you explicitly use
null coalescence operator |
Reference
types can accept null values |
Value
types cannot involve in inheritance. You cannot consider value type
as a base class and derive from it further. However, there is an exception
with structures. Structures cannot be derived further but they can
implement one or more interfaces |
Reference
types can be inherited further. For example assume that you have a
class called sampleClass. You can inherit from it and create a new
derived class sample2Class which can override properties and methods
of base class |
Memory
used by the value type available in the stack will be freed when the
value type variable has gone out of scope |
Memory
management is automatically taken care of by garbage collector |