Home > Programming > A brief note on value type and reference types

A brief note on value type and reference types

A brief note on value type and reference types

Value type variables simply associate a data in memory to a name. The size of the memory slot is dependent on the type of the variable. For example,

int a = 10;

There is a slot of 4 bytes (for integer type) on the stack and the name for the slot is ‘a’.

Reference type variables always point to a location on the heap. The size of a reference type variable is always 4 bytes (32 bit systems, 8 bytes in 64 bit systems). This 4 byte reference points to the actual data on the heap.

1. reference variables created on stack get destroyed when the stack unwinds (e.g. control exits out of the function). Note here that the actual data this variable was referring to will stay in memory as long other variables are referring it.

So irrespective of value type or reference type, all local variables are stored on stack.

2. Function parameters are also local to the function and stored on stack. However if the parameter has an ‘ref’ modifier then this argument shares the slot with the variable in the calling function.

3. Instances of a value type are stored in the same context as the variable that declares the value type. For example if a struct (value type) is defined as a data member in a class (reference type) then in all instance of the class, this struct instances will be created on heap.

4. Static variables and strings are always stored on the heap. Static variables are NOT stored on the garbage collected heap but on a different one called the high frequency heap.

5. If you declare two strings in a class like
string s1 = “ABC”;
string s2 = “ABC”;

note that both have same value. In such cases only one “ABC” is created on the heap and s1 and s2 will be referring to this memory location. If either s1 or s2 gets changed then a new string is created.

Further reading:
1. What is “ArrayList” and what are its uses
2. What is boxing in .net and why is this important
3. what are generics in .net 2.0 and what problem do they solve?

Categories: Programming
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: