The difference between passing by reference and by value in C # and the usage of ref and out keywords

Source: Internet
Author: User
Tags readline sort
The following is the difference between passing by reference and by value in C #, and the use of ref and out keyword is analyzed in detail, the need of friends can come over reference copy code code as follows:


/give three integers a small to large sort and sum and its average


//wherein, the results of three of the ordered integers and their ordering are passed by reference parameters, and are passed by the output parameter, and the average is returned by the return value.


//In the main () method to achieve the input of three integers and the output of the result


//Purpose: Define method, call method, understand referential transitive relation of formal parameter and argument, familiarize with reference parameter and output parameter.


using System;


class Class1


 {


//x,y,z is a formal parameter and is passed by value


static void Sort (int x, int y, int z)


    {


int temp=0;


if (x>y)


       {


temp=x;


x=y;


y=temp;


       }


if (y>z)


       {


temp=z;


z=y;


if (x>temp)


          {


y=x;


x=temp;


          }


Else


          {


y=temp;


          }


}


Console.WriteLine ("The sorted list is {0},{1},{2}", x,y,z);


x=x+y+z;


    }

I,j,k,total is a formal parameter, passed by reference (ref parameter, out parameter, is passed by reference)
Static double Average (ref int i, ref int J, ref int k, out int total)
{
Double L = 0;
Total = I+j+k;
I=total;
L= (Double) (total/3.0);
return l;
}

static void Main ()
{
A,b,c is an argument that is to be assigned to the formal parameter i,j,k,total;
int A, b, C;

Declare out parameter result, you can not initialize it
int result;

Console.Write ("Please enter the" a = ");
A = Convert.ToInt32 (Console.ReadLine ());
Console.Write ("Please enter the second number B =");
b = Convert.ToInt32 (Console.ReadLine ());
Console.Write ("Please enter the third number c =");
c = Convert.ToInt32 (Console.ReadLine ());

Sort (A,B,C);

In the Sort (int x, int y, int z) functions, formal parameter x,y,z are passed by value, so even if there is x=x+y+z in the function, the argument a value is unchanged.
Console.WriteLine ("The original value of/" A/"is {0}, it hadn ' t been changed in spite" + "of manipulating the Sort () metho D, because it is transmitted by a Value para/"x/"! ", a);

Average (ref int i, ref int J, ref int k, out int total) function, the formal parameter a,b,c,result are all//are passed by reference, after execution the argument a value changes.
Console.WriteLine ("The average result are {0}", average (ref a,ref B,ref C, out result));
The ref parameter must be initialized several years before the method is invoked.
The out parameter is not initialized until the method is invoked, and they are passed by reference

Console.WriteLine ("The Value of/" A/"has been changed due to the Average () method" + "are manipulated, and it is TRANSM Itted by a ref para/"ref i/"! Now it is {0}! ", a);

Console.ReadLine ();
}
}


Questions and answers:

1, when the value is passed, why does the change of the parameter value in the called method not affect the corresponding argument?
a : because when passed by value, the system first allocates memory space for the parameters of the method being invoked, and then "duplicates" the values in the arguments by position one by one to the formal parameters. The value stored in the formal parameter is only a copy of the argument, so any changes to the parameter values in the invoked method do not affect the corresponding formal parameters.

2, what is the difference between value passing and reference passing, what is a value parameter, and how does it pass?
a : when the value is passed, the system first allocates the memory space for the parameters of the invoked method and copies the value of the argument to the formal parameter by position one by one, thereafter, the parameters in the called method are worth any change without affecting the corresponding argument, and when the reference is passed, The system does not copy the value of the argument itself and passes it to the formal parameter. Instead, the reference value (that is, the address value) is passed to the formal parameter, so that the argument is referenced by the same variable as the passed argument, and the corresponding parameter in the method body is worth any change that affects the argument passed as a reference.

3, what is the formal parameter, what is the argument?
Answer:
Parameter:
parameters specified in the definition function are arguments, and they do not occupy memory cells when function calls are not present, only the formal parameters in the function are assigned to the internal deposit in the event of a function call. At the end of the call, the memory unit that the formal parameter occupies is also freed.

arguments: arguments can be constants, variables, and expressions, but require a definite value. Assigns the value of the argument to the formal parameter at the time of the call. In memory, the argument unit and the formal parameter unit are different units. When the function is invoked, the parameter is allocated a storage unit, and the value corresponding to the argument is passed to the formal parameter, and when the call is finished, the formal parameter unit is released and the argument unit retains the original value.

Understanding:
The argument is the thing to send in the method ~ ~ is to send in the thing in the method of copying processing, after processing the method will return a thing-return value.

When the value is passed, the argument is invariant ~ The parameter changes with the calculation ~ ~
When the pointer/reference passes the time ~ ~ How the argument changes ~ The argument is how to change ....

The transfer of parameters is divided into: 1. Value mode parameter transfer, 2. Reference mode parameter passing.
1) Passing by value (cannot change argument)
arguments are values such as variables, expressions, and so on.

When the function is called, the argument and the formal parameter exist in the memory in 2 fast different regions, the argument first copies a copy, and then passes the copy to the formal parameter. Because the copy is passed, the argument is not affected by the formal parameter, and the argument value is not changed.

2) delivered by address (can change argument)
The argument is a pointer/reference.

when the function is called, the pointer is to you, and the parameters are the same as the argument pointers, and any manipulation of the formal parameters equals the operation of the arguments. The value of the argument can be changed.

Impact on Parameters:
2 Types of data: value type + reference type
2 Types of parameters: Value pass + reference parameter (ref and out keyword);

The above four kinds of parameter's combination except the value passes the parameter way to pass the value type data, other combination method to the parameter operation all affects the parameter, will change!

value type: Simple Type (int,float,double,long,char,bool) + struct + enumeration
storage structure: data stored in the stack (stack: advanced out; single entrance, single outlet); High efficiency
Assignment Method: The value is passed

reference type: excluding Simple Type (int,float,double) + struct + enum types are reference data types. such as string;object; class; array; delegate; interface ...
Storage structure: Store address in stack, data in heap;
Assignment Method: The address of the data is passed.

Formal parameters : All known as "formal arguments" are parameters that are used when defining function names and body functions to receive parameters that are passed in when the function is called.
Arguments : all known as "actual parameters" are arguments that pass the function at call time.

The type of the formal parameter and argument must be the same or conform to the implied conversion rules.
When the parameters and arguments are not pointer types (that is, they are not passed by reference, but are passed by value),
When the function is run, the formal parameters and arguments are different variables,
They are in a different position in memory, the shape is arguments real
The contents of the parameter are copied, and the parameters are released at the end of the function.
And the argument content does not change.

If the function's argument is a pointer type variable (passed by reference), the procedure for calling the function
, the address of the argument is passed to the function, which is also used inside the function body
The address of the argument, that is, the argument itself. So inside the function body
You can change the value of an argument.

The most important use to pass by reference is to implement the "operator" Overload!

The difference between a ref parameter and an out parameter is that the ref parameter must be initialized several years before the method is invoked. The out parameter is not initialized until the method is invoked, and they are passed by reference

After C + + has a "reference pass", "the change of formal parameters does not affect the actual parameters" is sentenced to invalid. Because the function is passed to not a value, but the variable itself. A formal parameter defined in a function is still a local variable, but is a reference. Although the scope of this reference is limited to the inside of the function, because it is the same as the argument, the operation on it is exactly equivalent to the operation of the argument. For example, you call "Black cyclone" to buy fish, or "iron ox" to buy fish, go to the same person.

Why does C + + have a "reference to pass" thing? One argument is that only references can achieve the purpose of operator overloading, which we'll talk about later. However, aside from this, formal parameters are not references, which directly affect the efficiency of program execution. As mentioned earlier, the function call is to use the value of the argument to the initial Huafing parameter, the initialization process involves defining a variable and assigning it a value of two processes, and if the variable is not an intrinsic variable but rather a class object, defining a class object can be complex, and initializing the object can be complex. The reference simply takes an alias for the object, does not involve definition and initialization, and does not need to be freed from the scope.

By contrast, passing pointers can avoid the definition, initialization, and release of class objects. You only need to pay for the definition, initialization, and release of the pointer variable. However, the pointer's lethality is too great. Even skilled programmers can not guarantee the "wild pointer", the cost of the wild needles almost without exception is the program crashes.

The reference is not vegetarian, if the pointer passing is "to help you with a key to my home", then the reference transmission is directly to the property of my home to you. Sometimes we use reference passing only for efficiency, not for arguments to be modified, so remember to mark the parameters as const, such as "UINT getlength (const cstring&)."

By the way, pointer passing can also do so. Defining a parameter as a pointer to a const object (rather than a const pointer) can reduce lethality and protect the memory corresponding to the argument. If a normal value is passed, then there is no const effect outside the function. But I personally think it's a good thing to add a const sometimes. If the logic of the program does not need to change the parameters, and actually mistakenly write the code, plus const can let the compiler help us find bugs.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.