Reprint: Analysis of the difference between ref and out in C #

Source: Internet
Author: User

This article mainly introduces the difference between ref and out in C #, when a method needs to return multiple values, it needs to use ref and out, then the two methods are different, the need for friends can refer to the next

When you use a method to get the return value in C #, you usually get only one return value. Therefore, when a method needs to return multiple values, it needs to use ref and out, then what is the difference between these two methods?

Msdn:
The REF keyword enables parameters to be passed by reference. The effect is that when control is passed back to the calling method, any changes made to the parameter in the method are reflected in the variable. To use the ref parameter, both the method definition and the calling method must explicitly use the REF keyword.
The Out keyword causes parameters to be passed by reference. This is similar to the REF keyword, except that the ref requires that the variable be initialized before it is passed. To use an out parameter, both the method definition and the calling method must explicitly use the Out keyword.

Case:

Defines a method that evaluates to the maximum, minimum, and average values in an array of integers. If there is only one return value for a method, it is only possible to define a method for each one, but with ref and out it is much easier to implement.

Ref

Copy CodeThe code is as follows:
static int Getintresult (int[] arry, ref float AVG, ref int max, ref int min)
{
int sum = 0;
max = arry[0];
min = arry[0];
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;
}

Then try calling the method in the console:

Copy CodeThe code is as follows:
static void Main (string[] args)
{
Int[] arr = {1,2,3,4,5,6,7,8,9};
float avg;
int Max;
int min;
int sum = Getintresult (arr, ref AVG, ref max, ref min);
}

At this point the compiler will prompt for the red line, error: Using Unassigned Avg,max,min

Copy CodeThe code is as follows:
static void Main (string[] args)
{
Int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
float avg = 0;
int max = 0;
int min = 0;
int sum = Getintresult (arr, ref AVG, ref max, ref min);
Console.WriteLine ("Sum: {0}\t mean: {1}\t maximum: {2}\t minimum: {3}", Sum, AVG, Max, min);
Console.read ();
}

Operation Result:

Summarize:

Ref this keyword tells the C # compiler to pass a parameter value that points to the same memory as the variable in the calling code. Thus, if the called method modifies the values and returns, the variables of the calling code are modified.

The REF keyword enables parameters to be passed by reference. The effect is that when control is passed back to the calling method, any changes to the parameters in the method are reflected in the variable (the initial value of Avg,max,min is 0, and the value changes after the call method). To use the ref parameter, both the method definition and the calling method must explicitly use the REF keyword.

Out

After switching out, the above method is no longer applicable, error: Control must be assigned to the Out parameter "Min" and "Max" before leaving the current method. You will find here that Max and Min are not initialized outside of the loop. That's why it goes wrong.

Modified code:

Copy CodeThe code is as follows:
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;//When you use the Out keyword, you do not need to initialize it here, and the initialization does not affect the value inside the method, so your initialization is useless
int Max;
int min;
int sum = Getintresult (arr, out AVG, out Max, out min);
Console.WriteLine ("Sum: {0}\t mean: {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 you use the Out keyword, you must initialize the arguments that are decorated with the Out keyword before you leave 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;
}
}
}

The result is the same as above.

Summarize:
The Out keyword causes parameters to be passed by reference. This is similar to the REF keyword, except that the ref requires that the variable be initialized before it is passed. To use an out parameter, both the method definition and the calling method must explicitly use the Out keyword.

Conclusion:

The only difference between the keyword "ref" and "out" is that the keyword "out" does not require the calling code to initialize the parameter values to be passed. So when does the keyword ' ref ' work? You should use the keyword "ref" When you need to make sure that the calling method has initialized the parameter value. In the example above, the ability to use "out" is because the method being called does not depend on the value of the passed variable. The taste is slowly realized ...

Reprint From:http://www.jb51.net/article/59456.htm

Reprint: Analysis of the difference between ref and out in C #

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.