
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
1066
|
Chapter 19: Unsafe Code
19.1 Controlling Changes to Pointers Passed
to Methods
Problem
You must pass a pointer variable to a method; however, you do not want to allow
the called method to change the address that the pointer points to. For example, a
developer wants to assume that, after passing a pointer parameter to a method, the
parameter is still pointing to the same address when the method returns. If the called
method were to change what the pointer pointed to, bugs could be introduced into
the code.
In other cases, the converse may be true: the developer wants to allow the address to
be changed in the method she passes the pointer to. Consider a developer who might
create a method that accepts two pointers and switches those pointers by switching
the memory locations to which each pointer points to, rather than swapping the val-
ues each pointer points to.
Solution
You must decide whether to pass a pointer by value, by reference, or as an out
parameter. There are several ways to pass pointers to methods. These include using
or not using the
ref or out keyword to define how the parameters are to be handled.
To make sure that a method does not modify the pointer itself, pass the pointer by
value, as shown here:
unsafe
{
int num = 1;
int* numPtr = #
ModifyValue(numPtr);
// Continue ...