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() { 0123 };         
           Console.WriteLine("Pass by Value");
           PassByValue(arrayList);
        
           // What should be the output of below line ??
           Console.WriteLine(arrayList[1]);

           arrayList = new ArrayList() { 0123 };
           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() { 101102103104 };
        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() { 101102103104 };
        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

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives