Thursday, 6 November 2014

Reference Type And Value Type in C#

Introduction:  The Types in .NET Framework are either treated by Value Type or by Reference Type. A Value Type holds the data within its own memory allocation and a Reference Type contains a pointer to another memory location that holds the real data. Reference Type variables are stored in the heap while Value Type variables are stored in the stack.

   This article will give you a clear insight on what happens when a reference type is passed by value and what would happen when it is passed by reference.

Value Type:

A Value Type stores its contents in memory allocated on the stack. When you created a Value Type, a single space in memory is allocated to store the value and that variable directly holds a value. If you assign it to another variable, the value is copied directly and both variables work independently. Predefined datatypes, structures, enums are also value types, and work in the same way. Value types can be created at compile time and Stored in stack memory, because of this, Garbage collector can't access the stack.

e.g.

int x = 10;

Here the value 10 is stored in an area of memory called the stack.

Reference Type:

Reference Types are used by a reference which holds a reference (address) to the object but not the object itself. Because reference types represent the address of the variable rather than the data itself, assigning a reference variable to another doesn't copy the data. Instead it creates a second copy of the reference, which refers to the same location of the heap as the original value. Reference Type variables are stored in a different area of memory called the heap. This means that when a reference type variable is no longer used, it can be marked for garbage collection. Examples of reference types are Classes, Objects, Arrays, Indexers, Interfaces etc.

e.g.

int[] iArray = new int[20];
In the above code the space required for the 20 integers that make up the array is allocated on the heap.

Write down the following code and try guessing the output without running the program:

class Program{
    
static void Main(string[] args)
    {
           
// Pass reference type by value
           ArrayList arrayList = new ArrayList() { 0, 1, 2, 3 };         
           Console.WriteLine("Pass by Value");
           PassByValue(arrayList);
        
           // What should be the output of below line ??
           Console.WriteLine(arrayList[1]);

   
        arrayList = new ArrayList() { 0, 1, 2, 3 };
           Console.WriteLine("Pass by Reference");
           PassByReference(ref arrayList);

           // What should be the output of below line ??
          Console.WriteLine(arrayList[1]);
          Console.Read();
    }
    private static void PassByValue(ArrayList arrayList)
    {
        Console.WriteLine(arrayList[1]);
        
// Now Change the first position value        
        arrayList[1] = 90;
        arrayList = 
new ArrayList() { 101, 102, 103, 104 };
        Console.WriteLine(arrayList[1]);
    }
    private static void PassByReference(ref ArrayList arrayList)
    {
        Console.WriteLine(arrayList[1]);
        // Now Change the first position value
         arrayList[1] = 90;
         arrayList = 
new ArrayList() { 101, 102, 103, 104 };
        Console.WriteLine(arrayList[1]);
    }
}

Interpretation

First we'll take the case of passing value types by reference.

Let's have a look at the PassbyValue function:


The first line of code obviously would look out for value placed at second index in the arrayList and print out 1. After that, we change the value present at second index to 90. In the third line, since we had passed the reference type by value; it created a copy of original memory block pointing to the original memory location. But as soon we re-create the object, this loses the reference to the original memory location and acts as a different arrayList object then onwards. However, the changes done to the arrayList before the re-creation of object still persists. That's why, when we try to access the second index value, after the PassByValue function, we still get the output as 90.


Now, let's have a look at the Pass by Reference function:



Here too the first line of code output would be the same as reflected by the PassByValue function. The second would again change the value present at the second index to 90. In the third line, since we had passed the reference type by reference, it would just re-initialize its value to the new array (note that here the original memory location is getting new values overwritten here), thus the value for arrayList[1] inside the function would be 102 and after that the newly changed array would be referred everywhere, even outside the function.



Difference:



Conclusion
Passing reference types by Value creates a copy of the memory location and thus it is possible to change the value of the original reference type object inside the function (as soon we re-create that object). Passing reference types by ref doesn't create any copy of the object; it impacts the original reference object.

0 comments:

Post a Comment

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (9) Web Service (1) XMl (1)