The variables of value type store the real value, while the reference type variables store the references to the real objects.
The following code defines an int type variable. int type is a value type.
using System;
class Program
{
static void Main(string[] args)
{
int i = 5;
int j = i;
i = 3;
Console.WriteLine("i=" + i);
Console.WriteLine("j=" + j);
}
}
The output:
i=3
j=5
From the outputs we can see that the value of j
doesn't change even the value of i
is changed.
The value of i
is copied to j
when assigning the i
to j
.
A reference type variable has two parts: the object and its address.
A reference type variable stores the address of the object, not the object itself.
The following code creates a Rectangle class, which is a reference type.
using System;
class Rectangle
{
public int Width = 5;
public int Height = 5;
}
class Program
{
static void Main(string[] args)
{
Rectangle r1 = new Rectangle();
Rectangle r2 = r1;
Console.WriteLine("r1.Width:" + r1.Width);
Console.WriteLine("r2.Width:" + r2.Width);
r1.Width = 10;
Console.WriteLine("r1.Width:" + r1.Width);
Console.WriteLine("r2.Width:" + r2.Width);
}
}
The output:
r1.Width:5
r2.Width:5
r1.Width:10
r2.Width:10
In the main method two variable r1
and r2
are created. They both point to the same object.
We can see that as we change the width through r1
the r2.Width
gets the change as well.
+----+ +------------------+ +----+
| r1 | --->| rectangle object | <--- | r2 |
+----+ +------------------+ +----+
java2s.com | Contact Us | Privacy Policy |
Copyright 2009 - 12 Demo Source and Support. All rights reserved. |
All other trademarks are property of their respective owners. |