Summary of use of ref and out in C #

Source: Internet
Author: User
Tags variables variable
Ref is the address of the pass parameter, out is the return value, the two have some similarities, but there are different points.

You must assign a value to a variable before you use Ref.

The Out function empties the variable, even if the variable is already assigned, and all out referenced variables are assigned when the function is exited, and ref references can be modified or unmodified.

The difference can be referred to the following code:

Using System;
Class TESTAPP
{
static void Outtest (out int x, out int y)
{//You must assign values to X and y before leaving this function, or you will get an error.
y = x;
The above line error, because after using out, X and Y are emptied, need to be assigned a value, even if the call function before the value is not
x = 1;
y = 2;
}
static void Reftest (ref int x, ref int y)
{
x = 1;
y = x;
}
public static void Main ()
{
Out test
int a,b;
Before out use, variables can not be assigned a value
Outtest (out A, out B);
Console.WriteLine ("A={0};b={1}", a,b);
int c=11,d=22;
Outtest (out C, out D);
Console.WriteLine ("C={0};d ={1}", c,d);

Ref test
int m,n;
Reftest (ref m, ref N);
The line above is wrong, and before ref is used, the variable must be assigned a value

int o=11,p=22;
Reftest (ref o, ref P);
Console.WriteLine ("O={0};p ={1}", o,p);
}
}

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.