[C # Basics] differences between ref and out,

Source: Internet
Author: User

[C # Basics] differences between ref and out,

When using methods in C # to obtain the return value, only one return value is usually obtained. Therefore, when a method needs to return multiple values, it needs to use ref and out. What are the differences between the two methods?

MSDN:
The ref keyword allows the parameter to be passed by reference. The effect is that when the control is passed back to the call method, any changes made to the parameters in the method will be reflected in the variable. To use the ref parameter, you must explicitly use the ref keyword for both method definition and call methods.
The out keyword causes the parameter to be passed through reference. This is similar to the ref keyword, except that the ref requires that the variables must be initialized before being passed. To use the out parameter, the out keyword must be explicitly used for method definition and call.

Case:

Define a method to calculate the maximum, minimum, sum, and average values in an integer array. If a method can only have one return value, you can define only one method for each implementation, but it is much easier to implement it with ref and out.

Ref:

 1    static int GetIntResult(int[] arry, ref float avg, ref int max, ref int min) 2         { 3             int sum = 0; 4             max = arry[0]; 5             min = arry[0]; 6             for (int i = 0; i < arry.Length; i++) 7             { 8                 sum += arry[i]; 9                10                 if (max < arry[i])11                 {12                     max = arry[i];13                 }14                 if (min > arry[i])15                 {16                     min = arry[i];17                 }18             }19             avg = sum / arry.Length;20             return sum;21         }

 

Then we tried to call this method in the console:

1      static void Main(string[] args)2         {3             int[] arr = { 1,2,3,4,5,6,7,8,9};4             float avg;5             int max;6             int min;7             int sum = GetIntResult(arr, ref avg, ref max, ref min);8         }

In this case, the compiler will prompt you to draw a red line. Error: avg, max, min with no value assigned is used.

1 static void Main (string [] args) 2 {3 int [] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9 }; 4 float avg = 0; 5 int max = 0; 6 int min = 0; 7 int sum = GetIntResult (arr, ref avg, ref max, ref min); 8 Console. writeLine ("And: {0} \ t average: {1} \ t maximum: {2} \ t minimum: {3}", sum, avg, max, min ); 9 Console. read (); 10}
 

Running result:

Summary:

The keyword ref tells c # That the parameter value passed by the compiler points to the same memory as the variable in the call code. In this way, if the called method modifies these values and returns the result, the variables of the called code will be modified.

The ref keyword allows the parameter to be passed by reference. The effect is that when the control is passed back to the call method, any changes made to the parameter in the method will be reflected in this variable (the initial value of avg, max, min is 0, ). To use the ref parameter, you must explicitly use the ref keyword for both method definition and call methods.

Out:

After the value is changed to "out", the above method is no longer applicable and an error is returned. Error: You must assign values to the out parameter "min" and "max" before controlling the exit from the current method. You will find that max and min are not initialized out of the loop. Therefore, an error occurs.

Code after modification:

Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Threading. Tasks;

Namespace Wolfy. RefAndOut
{
Class Program
{
Static void Main (string [] args)
{
Int [] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9 };
Float avg; // The out keyword does not need to be initialized here, and initialization does not affect the internal values of the method. Therefore, Initialization is useless.
Int max;
Int min;
Int sum = GetIntResult (arr, out avg, out max, out min );
Console. writeLine ("And: {0} \ t average: {1} \ t maximum: {2} \ t minimum: {3}", sum, avg, max, min );
Console. Read ();
}
Static int GetIntResult (int [] arry, out float avg, out int max, out int min)
{
Int sum = 0;
Max = arry [0];
Min = arry [0]; // when using the out keyword, you must initialize the parameter modified by the out keyword before exiting the method.
For (int I = 0; I <arry. Length; I ++)
{
Sum + = arry [I];

If (max <arry [I])
{
Max = arry [I];
}
If (min> arry [I])
{
Min = arry [I];
}
}
Avg = sum/arry. Length;
Return sum;
}
}
}


1 using System; 2 using System. collections. generic; 3 using System. linq; 4 using System. text; 5 using System. threading. tasks; 6 7 namespace Wolfy. refAndOut 8 {9 class Program10 {11 static void Main (string [] args) 12 {13 int [] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9}; 14 float avg; // when the out keyword is used, initialization does not need to be performed here. Initialization does not affect the internal values of the method. Therefore, 15 int max is not used for initialization; 16 int min; 17 int sum = GetIntResult (arr, out avg, out max, out min); 18 Console. writeLine ("And: {0} \ t average: {1} \ t maximum: {2} \ t minimum: {3}", sum, avg, max, min ); 19 Console. read (); 20} 21 static int GetIntResult (int [] arry, out float avg, out int max, out int min) 22 {23 int sum = 0; 24 max = arry [0]; 25 min = arry [0]; // when the out keyword is used, you must initialize 26 for (int I = 0; I <arry. length; I ++) 27 {28 sum + = arry [I]; 29 30 if (max <arry [I]) 31 {32 max = arry [I]; 33} 34 if (min> arry [I]) 35 {36 min = arry [I]; 37} 38} 39 avg = sum/arry. length; 40 return sum; 41} 42} 43}

The result is the same as above.

Summary:
The out keyword causes the parameter to be passed through reference. This is similar to the ref keyword, except that the ref requires that the variables must be initialized before being passed. To use the out parameter, the out keyword must be explicitly used for method definition and call.

Conclusion:

The only difference between the keyword "ref" and "out" is that the keyword "out" does not require the parameter value to be passed during code initialization. When will the keyword 'ref "be used? When you need to ensure that the call method has initialized the parameter value, you should use the keyword "ref ". In the preceding example, "out" can be used because the called method does not depend on the value of the passed variable. A taste ......

After that:

In a forum, I accidentally saw such a post. By the way, I summarized it. I can also recall the basic knowledge of c.

Want to know more can see this article: http://www.cnblogs.com/dozer/archive/2011/10/28/ref-and-out-keywords.html

  • Blog: http://www.cnblogs.com/wolf-sun/
    Blog copyright: if there is something wrong or wrong in the text, you may point it out to avoid mistakes. If you think this article is helpful to you, [recommended! If you have better suggestions, leave a message to discuss them and make progress together! Thank you again for your patience in reading this article.

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.