Ref and out usage summary [ZT]

Source: Internet
Author: User
Ref and out usage summary [ZT]

1. The out must be initialized in the function body. It does not make sense to initialize it outside. That is to say, an out-type parameter cannot obtain the initial value passed in outside the function body.
2. Ref must be initialized in vitro.
3. Any modification to both functions will affect the external

Ref is the address for passing parameters, and out is the return value. There are some similarities between the two, but there are also differences.

You must assign values to variables before using ref.

The out function will clear the variable, even if the variable has been assigned a value, it will not work. When exiting the function, all variables referenced by the out function will be assigned a value, and the ref reference can be modified or not modified.

See the following code for differences:

Using system;
Class testapp
{
Static void outtest (Out int X, out int y)
{/Assign values to X and Y before leaving this function; otherwise, an error is returned.
/Y = X;
/The above line reports an error, because after the out is used, both X and Y are cleared, and the value must be assigned again, even if the value is assigned before the function is called.
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 is used, the variable can be assigned no 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 above line will go wrong. Before using ref, 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.