Working Of Reference Type And Value Type

Introduction

As most of you know, a reference type can be located in a managed heap, and a value type can be located in the stack. But many people want real examples of what makes them different in a programmer's world.

I tried to find out some tips about this considering four cases.

  1. Pure Value Type: which contains Value Type members.
  2. Pure Reference Type: which contains only Reference Type members.
  3. Value Type With Reference Type: A Value Type which contains both Value Types and Reference Types.
  4. Reference Type With Value Type: A Reference Type Which contains both Value Type and Reference Type.

You can see the differences when you assign one instance of a particular type to another instance of the same type. The core thing is that during an assignment, it assigns only a value, or it assigns both value and reference (memory location). Check the cases I mentioned below. Please download the source code along with this to find more yourself [I used the VS2005 WebProject Template].

Let's consider each case briefly.

  1. Pure Value Type: Here, I used a structure as a value type. It has an integer member. I created two instances of this structure. Afterward, I assigned a second instance to the first one. Then I changed the state of the second instance, but it didn't affect the first one, as whole items are value types, and assignments on those types will copy only values, not references, i.e., in a Value Type assignment, all instances have their own local copy of members.
  2. Pure Reference Type: I created a class and added a "DataTable" as a Reference Type member for this class. Then I performed the assignments just like below. But the difference is that on changing the state of the second instance, the state of the first instance will automatically alter. So in a Reference Type assignment, both Value and Reference will be assigned, i.e., all instances will point to the single object.
  3. Value Type With Reference Type: This case and the last case to come are more interesting. I used a structure in this particular scenario, too. But this time, it includes a Reference Type(A Custom Class Object) Member besides a Value Type (An Integer) Member. When you perform the assignments, it seems like a swallow copy, as the Value Type member of the first instance won't affected, but the Reference Type member will alter according to the second instance. So in this particular scenario, the assignment of a Reference Type member produced a reference to a single object, and the assignment of a Value Type member produced a local copy of that member.
  4. Reference Type With Value Type: Contrary to the above case, in this scenario, both Reference and value Types will be affected. i.e., a Value Type member in a Reference Type will be shared among its instances.

Happy coding.


Similar Articles