Reference Types

18 09 2008

Reference types that I mostly use are:

  • String – declared: string s="";
  • Exception – I usually declare this within the catch block that I am using it in. E.g. catch(Exception ex)
  • Array – declared: int[] ar = {3,2,1};

The important difference between value types and reference types is the way in which they are stored. A value type variable stores its data on the stack and any copies of the variable are allocated their own memory on the stack. A reference type variable stores its data on the managed heap with a memory pointer that points to a memory allocation on the stack. Any copies of the variable point to same memory allocation on the stack and therefore any changes are all being made to the same data.

For example, the following code:

variable1 += 1;
variable2 += 2;
Console.WriteLine("{0} , {1}" , variable1, variable2);

If variable1 and variable2 were value types, the output on the console screen would be "1,2"

If variable1 and variable2 were reference types, the output would be "3,3"

Advertisements

Actions

Information

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: