C #: Use the ref and out keywords to define the return value function

Source: Internet
Author: User
Code

Static   Int Xvalue ( Ref   Int Num, Ref   Int Num2)
{
Num =   2   * Num;
Num2 =   2   * Num2;
Return Num;
}
Static   Void Main ( String [] ARGs)
{
Int Num =   5 ;
Int Num2 =   10 ;
Console. writeline (xvalue ( Ref Num, Ref Num2 ));
Console. writeline (Num +   " : "   + Num2 );
// In this case, num = 10 and num2 = 20. The output result is 10: 20. Adding ref will affect the variables outside the function.
}

Two notes:
1: when defining a function, the Data Type of the specified parameter is the same as the variable type defined outside the function body. Static int xvalue (ref int num, ref int num2)
2: Add ref to each parameter using this function. If this parameter is not added, the value of the variable outside the function is not affected.

Code

Static   Int Maxvaluel ( Int [] Numarry, Out   Int Maxindex, Out   Int Maxindex2)
{
Int Maxvalue = Numarry [ 0 ];
Maxindex =   0 ;
Maxindex2 =   100 ;
For ( Int I =   1 ; I < Numarry. length; I ++ )
{
If (Maxvalue < Numarry [I])
{
Maxvalue = Numarry [I];
Maxindex = I;
}
}
Return Maxvalue;
}
Static   Void Main ( String [] ARGs)
{
Int Maxindex;
Int Maxindex2;
Int [] Numarr = { 14 , 3 , 34 , 11 , 99 , 33 };
Console. writeline (maxvaluel (numarr, Out Maxindex, Out Maxindex2 ));
// Returns the maxvalue variable in the function body.
Console. writeline (maxindex +   1 );
// Returns the maxindex variable in the function body.
Console. writeline (maxindex2 );
// Returns the maxindex2 variable in the function body.
Console. readkey ();
}

 

Two notes:
1: when defining a function, the Data Type of the specified output parameter is the same as the variable type defined outside the function body. The out int maxindex and out int maxindex2
2: use this function to add out to the output parameter.
The output here refers to outputting the variables in the function body to the function in vitro. This is also related to the scope of variables.

 

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.