Thursday 4 May 2017

Value & reference type in c#



C# has two different categories of data type:

1. value type.
2. Reference type.


Value type in c# stores its value directly, where as reference type stores a reference to a value.

There are simple types of variables in c# like integer and float. These are simply value type .Reference types are similar to types accessed through pointers in c++.
  
These two different types of variables stored in different places in memory. Value types are stored in stack memory, and reference types are stored in managed heap memory. Value and reference types assignment has different effects.

Consider x and y are type of int

x=10;

y=x;

now x and y will have the value 10.

 Now we change x=20;

The change in x will not affect the value in y. y will retain the old vale 10.

Because int is a value type, x and y are different locations in memory. .

Now consider rectangle as reference type:
 Rectangle r1,r2;

r1=new Rectangle();
  
r1.length=10;
r2=r1;

 Console.WriteLine(r2.length);

Above statement will print the output as:

10.
  
Now consider the following change.

r2.length=20;
  
Console.WriteLine(r1.length);
  
The above statement will give the output as:

20;

After executing the following line

r2=r1;

 There will be only one Rectangle object in memory . r1 , r2 both point to this Rectangle. Since both are referencing same memory location any change in one object will affect another object 

In c# basic data type bool is also  value type. In c# most complex data types including classes are reference data type.


                                                                          --------Muthu karthikeyan,,Madurai

No comments:

Post a Comment