1. Value parameters
When passing parameters to a method using values, the compiler makes a copy of the value of the actual parameter and passes this copy to the method. The called method does not pass the value of the actual parameter in the memory by modifying it, so when using the value parameters, the actual value can be guaranteed to be safe. When calling a method, if the type of the formal parameter is a value parameter, the value of the called actual parameter must be guaranteed to be the correct value expression. In the following example, the programmer does not achieve the purpose of his wish to exchange values:
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);
("i={0},j={1}",i,j);
}
}
Compile the above code and the program will output:
i=1,j=2
2. Reference parameters
Unlike value parameters, reference parameters do not open up new memory areas. When a formal parameter is passed to a method using reference parameters, the compiler will pass the address of the actual value in memory to the method.
In a method, the referenced parameter is usually initialized. Let’s look at the following examples.
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);
("i={0},j={1}",i,j);
}
}
Compile the above code and the program will output:
i=2,j=1
The Swap function is called in the Main function, x represents i and y represents j. In this way, the call successfully implements the value exchange of i and j.
Using reference parameters in methods can often cause multiple variable names to point to the same memory address. See example:
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 call of method G to F, the reference of s is passed to a and b at the same time. At this time, s, a, b points to the same memory area at the same time.