Analysis of the difference between ref and out in C #

Source: Internet
Author: User
Tags live chat

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


The 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:


The 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


The 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:


The 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;//does not need to be initialized here when using the Out keyword, and initialization does not affect the values inside the method, so you do not have to initialize

int max;

Int min;

int sum = Getintresult (arr, out AVG, out Max, out min);

Console.WriteLine (and: {0}\t mean: {1}\t max: {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 parameters 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;

}

}

}

In addition to the Declaration, Running GuestArticles are original, reproduced please link to the form of the address of this article
Analysis of the difference between ref and out in C #

This address: http://www.paobuke.com/develop/c-develop/pbk23212.html






Related content C # implements input 10 numbers into an array and asks for a sample of Max and Min and average devexpress treelist introduction C # Implementation of the 3D effect a complete example the fast ordering of C # recursive algorithm
Implementation code for C # Math processing odd-even-bit-in C # making simple multiplayer Live chat room C # customizing console-based Timer instances C # Verification Code recognition class full instance

Analysis of the difference between ref and out in C #

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.