Value Type Vs Reference Type

Value Type :

  1. When a value-type instance is created, a single space in memory is allocated to store the value.
  2. Primitive types such as integer, float, Boolean and char are also value types.
  3. Structure are value types.
  4. Memory Allocation : Value type local variable stored in Stack.
  5. C# parameters are (by default) passed by value.

Reference Type :

  1. With reference types, however, an object is created in memory, and then handled through a separate reference – rather like a pointer.
  2. Class is Reference types.
  3. Memory Allocation : The reference portion of reference type local variable store in Stack and content of reference type object store in Heap.

Examples :

   1: // Suppose Point is a struct, and Form is a class

   2: Point p1 = new Point();         // Point is a *struct*

   3: Form f1 = new Form();           // Form is a *class*

 

  • In the first case , one space of memory is allocated of p1 whereas in the second case, two spaces are allocated: one for a Form object and another for its reference (f1).
   1: Size s = new Size (100, 100);          // struct = value type

   2: Font f = new Font (“Arial”,10);        // class = reference type

   3:  

   4: // Form is Reference Type Variable

   5: Form myForm = new Form();

   6:  

   7: // To set the form's size and font, we can assign the objects s 

   8: //and f to the form via its properties:

   9: myForm.Size = s;

  10: myForm.Font = f;

               Here’s what it now looks like in memory:

image006

Advertisements

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