C # reference method parameter keywords: Params, ref, and out

Source: Internet
Author: User

No.1:

If you do not use ref or out when declaring a parameter for a method, the parameter can have an associated value. This value can be changed in the method, but the changed value is not retained when the control is passed back to the call process. You can change this behavior by using the method parameter keyword.

Params

The Params keyword specifies that the parameter method parameter is used when the number of parameters is variable. In the method declarationParamsNo other parameters are allowed after the keyword, and only one parameter is allowed in the method declaration.ParamsKeyword. Example:

Code
// Keywords_params.cs
Using system;
Class app
{
Public static void useparams (Params object [] list)
{
For (INT I = 0; I <list. length; I ++)
{
Console. writeline (list [I]);
}
}

Static void main ()
{
// The general practice is to first construct an object array and then use this array as a parameter of the method.
Object [] arr = new object [3] {100, 'A', "keywords "};
Useparams (ARR );

// After using the Params modifier parameter, we can directly use a group of objects as parameters
// Of course, this set of parameters must meet the parameter requirements of the called Method
Useparams (100, 'A', "keywords ");
Console. Read ();
}
}

 

Ref

RefKeyword to pass Parameters by reference. The effect is that when the control is passed back to the call method, any changes made to the parameters in the method will be reflected in the variable.

  1. To use the ref parameter, both the method definition and the call method must be explicitly used.RefKeyword.
  2. Parameters passed to the ref parameter must be initialized first. Unlike out, out parameters do not need to be explicitly initialized before being passed.
  3. Attributes are not variables, so they cannot be passed as REF parameters.
  4. While ref and out are processed differently at runtime, they are processed in the same way during compilation. Therefore, if one method uses the ref parameter while the other method uses the out parameter, the two methods cannot be reloaded. For example, from the compilation perspective, the two methods in the following code are exactly the same. If you try to do so, the Code cannot be compiled.
  5. If one method uses the ref or out parameter, and the other method does not use the two parameters, you can perform the overload.

Example: it is useful to pass the value type by reference, but ref is also useful for passing the reference type. This allows the called method to modify the object referenced by the reference, because the reference itself is passed by reference:

Code
// Keywords_ref.cs
Using system;
Class app
{
Public static void useref (ref int I)
{
I + = 100;
Console. writeline ("I = {0}", I );
}

Static void main ()
{
Int I = 10;

// View the value before calling the Method
Console. writeline ("before the method calling: I = {0}", I );

Useref (Ref I );

// View the value after the method is called
Console. writeline ("after the method calling: I = {0}", I );
Console. Read ();
}
}

/**//*
Console output:
Before the method calling: I = 10
I = 110.
After the method calling: I = 110
*/

 

Out

OutKeyword causes the parameter to be passed through reference. This is similar to the ref keyword.

Differences from Ref:

  1. Ref requires that the variables be initialized before being passed.
  2. Although the variables passed as the out parameter do not need to be initialized before being passed, you need to call a method to assign values before the method returns.

Example: in a different way from the ref example, you only need to change the ref to out, and then the variable I only needs to be declared:

Static void main ()
{
// Int I = 10; changed
Int I;
//
}

 

 

========================================================== =

No. 2:

First, let's review the syntax and elements of C # declaring a method. [] indicates Optional:
[Access modifier] Return Value Method Name ([parameter type] data type parameter name)
{Method body}

This article mainly aims to explain the optional [parameter type] In the parameter table. The setting of this parameter type affects the result of the operation on the parameter or the method of calling the method.

In C #, there are four parameter types:
1. None: Default, common Parameter
2. Params: Variable Length Parameter
3. Out: output variable
4. Ref: Reference Transfer

For a common parameter, if the parameter is a value type, the value is transferred. If the parameter is a reference type, the address is transferred. This is skipped because all types of C # books will talk about it.

Params parameters are used together with arrays to implement an array parameter of an indefinite length.
The most common method is console. writeline. One overload is as follows:
Public static void writeline (string formatstring, Params object [] values );
Common call Methods: console. writeline ("width: {0}, height: {1}", this. Width, this. Height );
The preceding "width: {0}, height: {1}" is loaded with formatstring
This. Width, this. height is loaded into values [0] and Values [1]. If we add a few more parameters, we will continue to store them in the array by subscript.

 

An out-type parameter is used as an output parameter. It is used to return multiple value-type variables in a single method. It is generally used for the value type.
Definition method:
Void test (Out int V1, out float V2)
{
V1 = 1;
V2 = 0.5f;
}
Call method:
Int;
Float B;
Test (out a, out B );

A parameter of the ref type is passed by reference when a variable is passed as a parameter to a method.
If the variable is of the value type, the effect of ref and out is the same, but the ref parameter must be assigned a value before use, rather than out.
Definition method:
Void test (ref int V1, ref float V2)
{
V1 = 1;
V2 = 0.5f;
}
Call method:
Int A = 0;
Float B = 0;
Test (Ref A, ref B );

 

What makes ref confusing is that if a parameter is a referenced variable, what is the difference between the processing result and directly passing a referenced variable?
Test class:
Public class class1
{
Public int x = 0;
Public int y = 5;
}
Definition method:
Private void test (class1 C)
{// Directly transfer the reference type
C. Y = 10;
C. x = 10;
// If the parameter is not passed by REF, the referenced memory space cannot be modified.
C = new class1 ();
}
Private void test (ref class1 C)
{// Use ref to pass the reference, allowing the called method to modify the object referenced by the reference, because the reference itself is passed by reference.
C. Y = 10;
C. x = 10;
// C is passed through ref. Here C will become a new class1
C = new class1 ();
}
Call method:
Class1 A = new class1 ();
Test ();
Console. writeline ("X: {0}, Y: {1}", A. X, A. Y );
Class1 B = new class1 ();
Test (ref B );
Console. writeline ("X: {0}, Y: {1}", B. X, B. y );
Output result:
X: 10, Y: 10
X: 0, Y: 5
The output result shows the difference between using no ref.
If ref is used, C can change the point to give up the memory space referenced by it.
If not, you can only change the data in the C memory.

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.