Value Types and Reference Types - Passing Value Types
(Page 2 of 4 )
When it comes to passing value types between methods, it is important to note that only a copy of the value is passed into the method. Any manipulations that you do to the copy will not affect the original value. Here is an illustration:
class Program
{
static voidMain(string[] args)
{
Pointp = new Point();
p.x = 2;
p.y = 7;
Console.WriteLine("Before an attempt to move the point: {0}", p);
Move(p, 2, 2);
Console.WriteLine("After the attempt to move the point: {0}", p);
}
static voidMove(Pointp, intx_value, inty_value)
{
p.x += x_value;
p.y += y_value;
}
}
struct Point
{
public intx;
public inty;
public override stringToString()
{
return string.Format("[{0},{1}]", x, y);
}
}
The output of the program will be:
Before an attempt to move the point: [2,7]
After the attempt to move the point: [2,7]
The first question that comes to mind is: what happened to the changes I made to the structure?
Answer: p is a Point, which is a structure, which is a value type. Passing a value type to a method results in a copy being made to the value type (p in this case). The copy is passed into the method and changes are made to the copy (the copy of p will have the values [4,9], the same value you anticipated for p). By the time you hit the closing bracket for the Move function, the copy of p will be out of scope. So, you never changed p, you only changed a copy of p.

Considering that parameters are passed via a value by default, the question is: is there any way to change that behavior? Yes, that is done using therefmodifier. If you place therefmodifier in front of a value parameter, the parameter is then passed via reference instead, and obviously any changes that you make to the parameter will be maintained after the method exits. Keep in mind, though, therefmodifier needs to be placed in the method declaration and the method call. If we return to the structure example, here is how it will look:
class Program
{
static voidMain(string[] args)
{
Pointp;
p.x = 2;
p.y = 7;
Console.WriteLine("Before an attempt to move the point: {0}", p);
Move(refp, 2, 2);
Console.WriteLine("After the attempt to move the point: {0}", p);
}
static voidMove(ref Pointp, intx_value, inty_value)
{
p.x += x_value;
p.y += y_value;
}
}
struct Point
{
public intx;
public inty;
public override stringToString()
{
return string.Format("[{0},{1}]", x, y);
}
}
Notice how the refmodifier is used in the Move() method (declaration and call).
Now the output of the program is changed to:
Before an attempt to move the point: [2,7]
After the attempt to move the point: [4,9]
Next: Reference Types >>
More C# Articles
More By Ayad Boudiab