Tuesday, August 28, 2012

Value types and reference types in c#.


 
 

 

C# has two different categories of data type:

 

  1. value types
  2. Reference types.

 

Value types 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 and r2 both point to this Rectangle  memory. Because r1 and r2 are variables of reference types declaring each variable just makes a reference. It doesn’t instantiate object . because r1 and r2 refer to the same object , changes made to r1 will affect r2 and vice versa.

 

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

 

 

No comments:

Post a Comment