Value Type and Reference Type in C#
Value Type and Reference Type
Value Type:
A data type is a value type if it holds a data value within its own memory space. It means the variables of these data types directly contain values.
All the value types derive from System.ValueType, which in-turn, derives from System.Object.
For example, consider integer variable int i = 100;
The system stores 100 in the memory space allocated for the variable i. The following image illustrates how 100 is stored at some hypothetical location in the memory (0x239110) for 'i':
Memory Allocation of Value Type Variable
The following data types are all of value type:
Bool
byte
char
decimal
double
enum
float
int
long
sbyte
short
struct
uint
ulong
ushort
Reference Type
Unlike value types, a reference type doesn't store its value directly. Instead, it stores the address where the value is being stored. In other words, a reference type contains a pointer to another memory location that holds the data.
For example, consider the following string variable:
string s = "Hello World!!";
The following image shows how the system allocates the memory for the above string variable.
Memory Allocation of Reference Type Variable
As you can see in the above image, the system selects a random location in memory (0x803200) for the variable s. The value of a variable s is 0x600000, which is the memory address of the actual data value. Thus, reference type stores the address of the location where the actual value is stored instead of the value itself.
The followings are reference type data types:
String
Arrays (even if their elements are value types)
Class
Delegate
Example: Passing Reference Type Variable
static void ChangeReferenceType(Student std2)
{
std2.StudentName = "Steve";
}
Comments
Post a Comment