Value Type Vs Reference Type a Simple Practical Study -c#

. Wednesday, August 24, 2011
  • Agregar a Technorati
  • Agregar a Del.icio.us
  • Agregar a DiggIt!
  • Agregar a Yahoo!
  • Agregar a Google
  • Agregar a Meneame
  • Agregar a Furl
  • Agregar a Reddit
  • Agregar a Magnolia
  • Agregar a Blinklist
  • Agregar a Blogmarks

Hi Guys, Want to tell you today regarding some of my good experience about Value Type vs Reference Type.

Value Type :
Value Type is a memory allocation technique in which memory allocated to a separate memory block which finally get "pushed onto Stack.

Basic Example : Structure.
Type of Memory Allocation :Static

Reference Type 
Reference Type is another memory allocation technique is a memory management technique in which two things are comes into picture :
1.Stack
   used to store reference variable with its values.
2.Heap
   used to store object variable which stores the actual content.

Basic Example : Class
Type of Memory Allocation : Dynamic.

Now lets see this by an Example

1. I created one structure and one class as follows :


struct Strct
    {
        public int x, y;
    }

class Cls
    {
        public int p, q;
    }

And a Main class to call them.


 class Program
    {
        static void Main(string[] args)
        {
         
         }
   }


Now onwards I'll tell you the programming logic behind them

Scenario 1:

lets create one Instance for each of them as follows :
            Strct MainInstance = new Strct();

            Cls MainObject=new  Cls();
allocate some value for each of them as follows :
            MainInstance.x = 3;
            MainInstance.y = 4;
            MainObject.p = 3;
            MainObject.q = 4;

Now I Invoke a Test Function to check the actual situation

 Test(MainInstance,MainObject);

and This Test Function Defined as follows :


 public static void Test(ref Strct tmpstrc,ref Cls tmpcls)
        {
            tmpstrc.x = 1;
            tmpstrc.y = 2;
            tmpcls.p = 1;
            tmpcls.q = 2;
         
        }

My final code is something like this inside main


     static void Main(string[] args)
        {
            Strct MainInstance = new Strct();
            Cls MainObject=new  Cls();
            MainInstance.x = 3;
            MainInstance.y = 4;
            MainObject.p = 3;
            MainObject.q = 4;
            Test(MainInstance,MainObject);
            Console.Write("Value of Instances are {0}{1}", MainInstance.x, MainInstance.y);
            Console.Write("\n");
            Console.Write("Value of Objects are {0}{1}", MainObject.p, MainObject.q);
            Console.Read();
        }

So Guys What the Value you expect here ....

Output
Value of Instances are 3 4
Value of Objects are  1 2

B'caz Structure(Value Type) stores values separately for each variable where as Class(ReferenceType) there is allocated object reference variable which points to object of class.

so in this scenario two separate variables are created for Structure
MainInstance(3,4)
tmpstrc(1,2)

and two reference variables which references to Class
MainObject(3,4)
tmpcls(1,2)

but here we actually copied the reference of tmpcls to MainObject so this also holds the same reference now.

Scenario 2:

now I made a little bit changes inside Test function.


public static void Test(Strct tmpstrc,Cls tmpcls)
        {
              tmpcls=null;
        }


Well, what the output you expect now.

its


Value of Instances are 3 4
Value of Objects are  3 4

For Instance case its very clear b'caz each time a separate variable holds the values.
Incase of Objects this display 3 4 b'caz this time reference which is copied is null so the actual reference will works for MainObject reference variable and this will show those values which were allocated earlier.


Scenario 3: 

the last and the most important situation here occurs when we use "ref" keyword.

look at Test function Declaration
Test(ref MainInstance,ref MainObject);

and its Declaration


public static void Test(ref Strct tmpstrc,ref Cls tmpcls)
        {
            Console.Write("Copied Object{0}{1}", tmpcls.p, tmpcls.q);
            Console.Write("\n");
            Console.Write("Copied Instance{0}{1}", tmpstrc.x, tmpstrc.y);
            Console.Write("\n");
            tmpstrc.x = 1;
            tmpstrc.y = 2;
            tmpcls.p = 1;
            tmpcls.q = 2;
        }


Now What the output you expect


 Copied Object 3 4
 Copied Instance 3 4
 Value of Instances are 1 2
 Value of Objects are  1 2

In case of memory variable (Value Type) we have Interchange each values with each other.
eg: MainInstance now referes to tmpstrc and vice-versa.
In case of reference variable(Reference Type) we have Interchange their references with each other.
eg : MainObject now having reference of tmpcls and vice-versa.

but wait a minute If I set the following :
   tmpcls=null;
inside our Test Function defination then what will happend ?

This time this will executes upto displaying memory variable MainInstance but when the execution comes at
Console.Write("Value of Objects are {0}{1}", MainObject.p, MainObject.q);

this throws Null reference exception b'caz this time reference hold by MainObject(which was hold by tmpcls before sometime is null) and we are trying to display its values so this exception will be generated.

so Guys !!! Hope you enjoyed this article .catch you soon with some other stuff.










1 comments:

Rana Mukherjee said...

Hi,

First scenario is not possible where you written Test(ref Strct tmpstrc,ref Cls tmpcls) and calling Test(MainInstance,MainObject), it will give you a complie time error.

Thanks,
Rana