Out and Ref parameters in C #

Source: Internet
Author: User

OutAndRefParameters are often used to get values by passing parameters through methods. When your method does not have more than one return value, these two parameters play a role. 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. In this article, I will explain how to use these two parameters in the c # application.

1,OutParameters

OutThe method parameter keyword allows the method reference to pass to the same variable of the method. When the control is passed back to the call method, any changes made to the parameters in the method will be reflected in this variable.

Public class mathClass
{
Public static int TestOut (out int iVal1, out int iVal2)
{
IVal1 = 10;
IVal2 = 20;
Return 0;
}

Public static void Main ()
{
Int I, j; // variable need not be initialized
Console. WriteLine (TestOut (out I, out j ));
Console. WriteLine (I );
Console. WriteLine (j );
}
}

 

2,RefParameters

RefThe method parameter keyword allows the method reference to pass to the same variable of the method. When the control is passed back to the call method, any changes made to the parameters in the method will be reflected in this variable.

 

Static void Main (string [] args)
{
// Ref sample

Int refi; // variable need not be initialized

Refi = 3;

RefTest (ref refi );

Console. WriteLine (refi );

Console. ReadKey ();

}

Public static void RefTest (ref int iVal1)

{

IVal1 + = 2;

}

 

3. 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.

 

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.