[Original] similarities and differences between ref and out in C #

Source: Internet
Author: User

In C #, you can pass parameters either by value or by reference. PASS Parameters by referencing, allow the Members in the method to change the parameter value and keep the changes. To pass parameters through references, you can use the ref and out keywords. The ref and out functions are equivalent to pointers in C.

Both ref and out allow parameters to be passed by reference, but there are some differences between them.

1. The ref parameter must be initialized first, but the out parameter does not need to be initialized first, but must be initialized in the method.

2. Out is suitable for use where multiple retrun return values are required, while ref is used when the caller's reference is modified by the method to be called.

3. When using ref and out, you must use the ref or out parameter before using and defining methods.

For details, see the following example:

Static   Void Main ( String [] ARGs)
{
Int I =   3 ;
Testref ( Ref I );
Console. writeline ( " Value after executing ref "   + I. tostring ());

IntJ;
Testout (OutJ );
Console. writeline ("Value after execution of out" +J. tostring ());
Console. Read ();
}

Static   Void Testref ( Ref   Int I)
{
Console. writeline ( " Value before auto-Increment "   + I. tostring ());
I ++ ;
Console. writeline ( " Auto-increment parameter value "   + I. tostring ());
}

Static   Void Testout ( Out   Int J)
{
J =   1 ;
Console. writeline ( " Value before auto-Increment "   + J. tostring ());
J ++ ;
Console. writeline ( " Auto-increment parameter value "   + J. tostring ());
}

Execution result:

From the above results, we can see that both ref and out are delivered by address.

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.