Differences between ref and out in C #

Source: Internet
Author: User

// If you encounter a problem today, you need to pass an initialized value to another function and return the incremental value.
// Sum up the difference between out and ref by the way
Private void button#click (object sender, EventArgs e)
{
// The ref and out parameters can be modified.
Int refInt = 100;
RefValue (ref refInt );
MessageBox. Show (refInt. ToString ());
// Www.2cto.com
Int outInt = 100;
OutValue (out outInt, 100 );
MessageBox. Show (outInt. ToString ());
}
// Ref
Public void RefValue (ref int refInt)
{
RefInt + = 100; // ref reference does not need to be initialized
}
// A function can have multiple ref Parameters
Public void RefValue (ref int refInt, ref int rInt)
{
RefInt + = 100; // ref reference does not need to be initialized
}
// Out
Public void outValue (out int outInt, int I)
{
OutInt = I + 100; // The out reference must be initialized.
}
/* The function cannot have multiple out parameters.
Public void outValue (out int outInt, out oInt, int I)
{
OutInt = I + 100; // The out reference must be initialized.
}*/

The difference between ref and out is that in C #, you can pass parameters either by value or by reference. You can pass a parameter through reference to allow function members to change the parameter value and keep the change. To pass parameters through references, you can use the ref or out keyword. Both the ref and out keywords provide similar functions, and they also act like pointer variables in C. Their differences are:
1. When using ref parameters, the input parameters must be initialized first. For out, initialization must be completed in the method.
2. When using ref and out, the Ref or Out keyword must be added to both the method parameters and the execution method. To match.
3. out is suitable for use where multiple retrun return values are required, while ref is used when the caller's reference is modified by the method to be called.
Note: in C #, there are four types of method parameters passed: by value, by reference, and output parameter (by output ), array parameters (by array ). There is no additional modifier for the value passing parameter. The address passing parameter requires the modifier ref, the output parameter requires the modifier out, And the array parameter requires the modifier params. If the value of the parameter is changed during a method call, the parameter passed in to the method does not change after the method call is completed, but retains the original value. On the contrary, if the value of the parameter is changed during the method call process, the parameters for passing in the method also change after the call is completed. In fact, we can clearly see the meaning of the two from the name-the pass-through parameter transfers a copy of the call parameter, while the transfer parameter passes the memory address of the call parameter, this parameter points to the same storage location inside and outside the method.
The ref method parameter keyword in the method parameter allows the method reference to pass to the same variable of the method. When the control is passed back to the call method, any changes made to the parameters in the method will be reflected in this variable.
To use the ref parameter, you must explicitly pass the parameter as the ref parameter to the method. The ref parameter value is passed to the ref parameter.
Parameters passed to the ref parameter must be initialized first. Compared with the out parameter, the latter parameter does not need to be explicitly initialized before being passed to the out parameter.
Attributes are not variables and cannot be passed as ref parameters.
If the declarations of the two methods are only different in their use of ref, an overload will occur. However, it is not possible to define a unique reload for ref and out.
Out
The out method parameter keyword on the method parameter enables the method reference to pass to the same variable of the method. When the control is passed back to the call method, any changes made to the parameters in the method will be reflected in this variable.
When you want the method to return multiple values, it is very useful to declare the out method. You can still return a value using the out parameter. A method can have more than one out parameter.
To use the out parameter, you must use the parameter as the out parameter to pass it to the method explicitly. The value of the out parameter is not passed to the out parameter.
You do not need to initialize the variable passed as the out parameter. However, the out parameter must be assigned a value before the method is returned.
The property is not a variable and cannot be passed as an out parameter.


There are many articles on the internet saying that ref only transmits values, out transmits addresses, and so on. It does not seem very accurate. The following is the sample code. You can try it:

Public int RefValue (int I, ref int j)
{
Int k = j;
J = 222;
Return I + k;
}

Public int OutValue (int I, out int j)
{
J = 222;
Return I + j;
}
Private void cmdRef_Click (object sender, EventArgs e)
{
Int m = 0;
MessageBox. Show (RefValue (1, ref m). ToString ());
MessageBox. Show (m. ToString ());
}
Private void cmdOut_Click (object sender, EventArgs e)
{
Int m;
MessageBox. Show (OutValue (1, out m). ToString ());
MessageBox. Show (m. ToString ());
}
According to a summary on the internet, ref is inbound and outbound, While outbound is outbound.
--------------------------------------------------------------------
Ref

We usually pass the value to the method. the method obtains a copy of these values, and then uses these copies. After the method is run, these copies will be discarded, and the original values will not be affected. in addition, we have other parameters passed to the method, including reference (ref) and output (out ).

Sometimes, we need to change the value of the original variable. In this case, we can pass the reference of the variable to the method, instead of the value of the variable. A reference is a variable that can access the value of the original variable. modifying a reference changes the value of the original variable. the value of a variable is stored in the memory. You can create a reference pointing to the position of the variable in the memory. when the reference is modified, the value in memory is modified, so the value of the variable can be modified. when we call a method that contains referenced parameters, the parameters in the method point to the corresponding variable passed to the method. Therefore, we will understand that, why does the modification of the Parameter Variable also lead to the value of the original variable.

Create a method for passing parameters by reference. Use the keyword ref. For example;

 

Using System;
Class gump
{
Public double square (ref double x)
{
X = x * x;
Return x;
}
}

Class TestApp
{
Public static void Main ()
{
Gump doit = new gump ();

Double a = 3;
Double B = 0;

Console. WriteLine (\ "Before square-> a = {0}, B = {1} \", a, B );

B = doit. square (ref );
Console. WriteLine (\ "After square-> a = {0}, B = {1} \", a, B );
}
}
Through the test, we found that the value of a has been changed to 9.
Out

By specifying the return type, you can return a value from the method. Sometimes (maybe we haven't met it yet, but we should have such a method), you need to return multiple values, although we can use ref, C # provides an attribute type with the keyword "out. after the introduction, we will explain the differences between ref and out.
 
By using the out keyword, we change the values of the three variables, that is, the out is the value transmitted from the method.
Using System;
Class gump
{
Public void math_routines (double x, out double half, out double squared, out double cubed)
// It Can Be: public void math_routines (// ref double x, out double half, out double squared, out double cubed)
// However, this is not allowed: public void math_routines (out double x, out double half, out double squared, out double cubed). In this example, because the output value depends on x, x cannot be used for the output value.
{
Half = x/2;
Squared = x * x;
Cubed = x * x;
}
}

Class TestApp
{
Public static void Main ()
{
Gump doit = new gump ();

Double x1 = 600;
Double half1 = 0;
Double squared1 = 0;
Double cubed1 = 0;
[Page]
/*
Double x1 = 600;
Double half1;
Double squared1;
Double cubed1;
*/

Console. WriteLine (\ "Before method-> x1 = {0} \", x1 );
Console. WriteLine (\ "half1 = {0} \", half1); Console. WriteLine (\ "squared1 = {0} \", squared1 );
Console. WriteLine (\ "cubed1 = {0} \", cubed1 );

 

Doit. math_rountines (x1, out half1, out squared1, out cubed1 );

Console. WriteLine (\ "After method-> x1 = {0} \", x1 );
Console. WriteLine (\ "half1 = {0} \", half1 );
Console. WriteLine (\ "squared1 = {0} \", squared1 );
Console. WriteLine (\ "cubed1 = {0} \", cubed1 );
}
}
We found that the ref and out functions seem to be the same. because the value of the variable passed to the method can be changed. however, the essential difference between the two is that ref is the incoming value, and out is the outgoing value. in a method that contains the out keyword, the variable must be assigned a value by a variable that does not include out (which can be ref) in the method parameter or by a global variable (that is, the external variable of the method that can be used by the method) variable assignment. The out principle is to ensure that every outgoing variable must be assigned a value.

You can directly use the/***/commented out part of the code above. that is to say, you can not initialize the variable before calling the method. however, \ "x1 \" requires a value. Otherwise, an error is returned. the ref parameter has a value when it is passed to the method, so the ref parameter focuses on modification. out focuses on output.

From the big meteorological learning field

Related Article

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.