C: the difference between a reference variable and a numeric variable

  • 2020-05-09 19:09:32
  • OfStack

1. The value of parameters
When a value is passed to a method, the compiler makes a copy of the argument's value and passes the copy to the method. The method being called does not modify the value of an argument in memory, so the actual value is guaranteed to be safe when using the value parameter. When calling a method, if the formal parameter is of type value, the value of the argument must be the correct value expression. In the following example, the programmer does not achieve what he wants to exchange values for:


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);
}
}

Compile the above code, the program will output:

i=1,j=2

2. Reference type parameters
Unlike value parameters, referential parameters do not open up new memory regions. When you pass formal parameters to a method with referential parameters, the compiler passes the actual in-memory address of the value to the method.

In a method, the reference type parameter is usually already initialized. Let's look at the following example.


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);
}
}

Compile the above code, the program will output:

i=2,j=1

 

The Swap function is called in the Main function, x for i and y for j. In this way, the call successfully implements the value exchange between i and j.

Using referential parameters in a method can often result in multiple variable names pointing to the same memory address. See the sample:


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 method G's call to F, a reference to s is passed to a and b at the same time. At this point, s,a,b all point to the same memory region.


Related articles: