Note the difference between the out keyword and the ref keyword!

Source: Internet
Author: User
I. Ref keywordsInt number = 2;

// The address of the variable number is passed.
Getdouble (ref number );

// The value is changed and the result output is 4
Console. writeline (number );

Static int getdouble (ref int num)
{
// The value of the original reference parameter is modified.
Return num = num * 2;
}

Ii. Out keywords

Static void changevalue (Out int PARAM)
{
// Internal function value assignment. If the value is not re-assigned, an error occurs!
Param = 2;
}

Static void main (string [] ARGs)
{
// You do not need to assign an initial value like ref.
Int number;

// Reference the same number
Changevalue (Out int number );

// Finally obtain the output value after the change from the function. The result is 2.
Console. writeline (number );
}

Summary:The difference between keyword ref and out. To put it simply,
1) ref refers to transferring the reference of a variable to the function. The variable must be assigned a value before passing the parameter;
2) The out variable must be initialized in the function and then returned to the outside. When the out keyword is used, you do not need to assign a value to the parameter before passing the parameter. Even if the parameter is assigned, the value must be re-assigned within the function.

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.