
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Controlling Changes to Pointers Passed to Methods
|
1067
SwitchXY(ref ptrx, ref ptry);
Console.WriteLine(*ptrx + "\t" + (int)ptrx);
Console.WriteLine(*ptry + "\t" + (int)ptry);
}
public unsafe void SwitchXY(ref int* x, ref int* y)
{
int* temp = x;
x = y;
y = temp;
}
The SwitchXY method switches the values of the x and y pointers so that they point to
the memory location originally pointed to by the other parameter. In this case, you
must pass the pointers in to the
SwitchXY method by reference (ref). This allows the
SwitchXY method to actually change the pointers and to return these modified pointers.
Discussion
In safe code, passing a value type to a method by value means that the value, not the
reference to that value, is passed in. Therefore, the called method cannot modify the
value that the calling method’s reference points to; it can modify only the copy that it
receives.
It works the same way with unsafe code. When an unsafe pointer is passed in to a
method by value, the value of the pointer (which is a memory location) cannot be
modified; however, the value that this pointer points to can be modified.
To examine the difference between passing a pointer by reference and by value, you
first need to set up a pointer to an integer:
int x = 5;
int* ptrx = &x;
Next, write the method that attempts ...