1. Value parameter
When an argument is passed by a value to a method, the compiler copies the value of the argument and passes the copy to the method. The invoked method does not pass through modify the value of an argument in memory, so when using a value parameter, the actual value is guaranteed to be safe. When a method is invoked, the value of the argument must be guaranteed to be the correct value expression if the type of the formal argument is a value parameter. In the following example, the programmer does not implement the purpose that he wants to exchange values:
Copy Code code as follows:
Using System;
Class Test
{
static void Swap (int x,int y) {
int temp=x;
X=y;
Y=temp;
}
static void Main () {
int i=1,j=2;
Swap (I,J);
Console.WriteLine ("I={0},j={1}", i,j);
}
}
Compiling the above code, the program will output:
i=1,j=2
2. Reference type parameter
Unlike value parameters, reference parameters do not open up new memory regions. When you pass a formal parameter to a method using a reference parameter, the compiler passes the actual value in the memory address to the method.
In a method, a reference parameter is usually initialized. Look at the example below.
Copy Code code as follows:
Using System;
Class Test
{
static void Swap (ref int X,ref int y) {
int temp=x;
X=y;
Y=temp;
}
static void Main () {
int i=1,j=2;
Swap (ref i,ref J);
Console.WriteLine ("I={0},j={1}", i,j);
}
}
Compiling the above code, the program will output:
I=2,j=1
The swap function is called in the main function, and X represents the I,y Representative J. In this way, the invocation succeeds in implementing the value exchange of I and J.
Using reference parameters in a method can often cause multiple variable names to point to the same memory address. See Example:
Copy Code code as follows:
Class A
{
string S;
void F (ref string A,ref string b) {
S= "one";
A= "two";
b= "Three";
}
void G () {
F (ref s,ref s);
}
}
During the invocation of method G to F, the reference to S is passed to both A and B. At this point, S,a,b also points to the same memory area.