Information Technology Reference
In-Depth Information
Reference Parameters
The second type of parameter is called a reference parameter .
When using a reference parameter, you must use the ref modifier in both the declara-
tion and the invocation of the method.
￿
￿
The actual parameter must be a variable, which must be assigned to before being used
as the actual parameter. If it is a reference type variable, it can be assigned a reference or
the value null .
For example, the following code illustrates the syntax of the declaration and invocation.
Include the ref modifier.
void MyMethod( ref int val ) // Method declaration
{ ... }
int y = 1; // Variable for the actual parameter
MyMethod ( ref y ); // Method call
Include the ref modifier.
MyMethod ( ref 3+5 ); // Error!
Must use a variable.
Remember that value parameters allocate memory on the stack for the formal parameters.
In contrast, reference parameters have the following characteristics:
￿
They do not allocate new memory on the stack for the formal parameters.
￿
A formal parameter name acts as an alias for the actual parameter variable, referring to
the same memory location.
Since the formal parameter name and the actual parameter name reference the same
memory location, clearly any changes made to the formal parameter during method execution
will be visible after the method is completed, through the actual parameter variable.
Search WWH ::




Custom Search