Parsing of parameters ref and out in C # methods

Source: Internet
Author: User
Tags modifiers

I. parameter types in C # methods

There are 4 types of parameters, sometimes it is difficult to remember their different characteristics, to make a summary, making it easier to compare and contrast.

Ii. parameters in the C # method

1. Value parameter

Use the value parameter to pass data to the method by copying the value of the argument to the formal parameter. Method is called, the system does the following:

· Allocating space for a parameter in the stack

· Copy arguments to formal parameters

Note: Stacks (advanced post-exit) are allocated memory space during compilation, so your code must have a clear definition of the size of the stack;

Heap (queue first, FIFO) is a dynamically allocated memory space during the program's run, and you can determine the size of the heap memory to allocate, depending on how the program is running.

/// <summary>///declaring Methods/// </summary>/// <param name= "value" >Parameters</param>/// <returns>return value</returns>Static floatFuncdata (floatvalue) {    floati =1.5F; floatj =2.5F; floatvalue1 = Funcdata (i);//Method Invocation    floatvalue2 = Funcdata (i+j);//method Invocation (the argument of a value parameter is not necessarily a variable.) It can be any expression that can be calculated as the corresponding data type)    returnValue1 +value2;}

2. Reference parameters

· When using reference parameters, you must use the ref modifier in both the declaration and the invocation of the method

· An argument must be a variable that must be assigned before it is used as an argument, and if it is a reference type variable, it can be assigned a reference or a null value

/// <summary>///declaring Methods/// </summary>/// <param name= "value" >Parameters</param>/// <returns>return value</returns>Static voidFuncdata (floatvalue) {    //Method Invocation    inttemp=0;//Real ParametricFuncdata (reftemp);//contains modifier ref//Funcdata (ref temp+1);//error, the variable must be used}/// <summary>///Method Declaration/// </summary>/// <param name= "value" >Parameters</param>/// <returns>return value</returns>Static intFuncdata (ref intvalue) {   returnValue = -;}

3. Output parameters

· Modifiers must be used in both declarations and invocations. The modifier for the output parameter is out, not ref

· Similar to reference parameters, arguments must be variables, not other types of expressions. (Because the method requires a memory location to hold the return value)

/// <summary>///declaring Methods/// </summary>/// <param name= "value" >Parameters</param>/// <returns>return value</returns>Static voidFuncdata (floatvalue) {    //Method Invocation    inttemp=0;//Real ParametricFuncdata ( outtemp);//contains modifiers out//Funcdata (out temp+1);//error, the variable must be used}/// <summary>///Method Declaration/// </summary>/// <param name= "value" >Parameters</param>/// <returns>return value</returns>Static intFuncdata ( out intvalue) {   returnValue = -;}

Unlike reference parameters, the output parameter has the following requirements:

· Inside the method, the output parameter must be assigned before it is read. (meaning that the initial value of the parameter is irrelevant and there is no need to assign a value to the argument before the method call)

· Before the method returns, any cross-through possible path inside the method must be assigned one time for all output parameters.

classMyClass { Public intval = -;}classprogram{/// <summary>    ///Method Declaration/// </summary>    Static voidFuncdata ( outMyClass MyClass, out inttemp) {MyClass=NewMyClass ();//To create a class variableMyclass.val = -;//assignment Fieldtemp= -;//Assignment int parameter    }    /// <summary>    ///Method Invocation/// </summary>    Static voidMain () {MyClass my=NULL; inttemp; Funcdata ( outMy outtemp);//Calling Methods    }    Static voidFunctest ( out intvalue) {        varTest = value+1;//error, unable to read output variable before method assignment    }}

4. Parameter array

• There can be only one parameter array in a parameter list

• If there is, it must be the last one in the list

Declaring a parameter array must do the thing

• Use the params modifier before the data type

• Place a set of empty brackets after the data type

/// <summary> /// declaring Methods /// </summary> /// <param name= "Array" > Parameters </param> Static void Functest (paramsint[] Array) {    ...}

· An array is a neat set of data items of the same type

· Arrays are accessed using a numeric index

· An array is a reference type, so all its data items are saved in the heap

Three, C # method parameter ref and out difference

1. When using a ref parameter, the passed-in parameter must first be initialized. For out, initialization must be done in the method.

2. When using ref and out, add the ref or out keyword to match the method's parameters and execution method.

3. Out is suitable for use where multiple return values need to be retrun, while ref is used to modify the caller's reference in a method that needs to be called.

classtestapp{Static voidOuttest ( out intX out inty) {//XY must be assigned before function or error//y = x; //above line error use Outxy all empty needs to be re-assigned even if the function before the call to assign a value linex =1; Y=2; }    Static voidReftest (ref intXref inty) {x=1; Y=x; }     Public Static voidMain () {//correct (out test)        intA, B; //Out pre-use variables to assign valuesOuttest ( outA outb); Console.WriteLine ("A={0};b={1}", A, b); //when you use the Out keyword, you do not need to initialize it here, and the initialization does not affect the value inside the method, so your initialization is useless        intc = One, d = A; Outtest ( outC outd); Console.WriteLine ("c={0};d ={1}", C, D); //error (ref test)        intm, N; Reftest (refMrefN); //above row error ref must be assigned before using the variable//correct (ref test)        into = One, p = A; Reftest (refOrefp); Console.WriteLine ("o={0};p ={1}", O, p); }}

Iv. Summary

1.Use of ref: When a parameter is passed with ref, it must be set to its initial value when it is created, and ref focuses on the modification;

2, outof use: when the Out parameter is passed, when the parameter is created, it can not set the initial value, but must be initialized in the method, out focus on the output;

Note: When you want a method to return multiple values, you can use out, and a parameter in one method can have one or more out parameters, and an out parameter must be explicitly passed to the method as an out parameter, but the value of the out parameter is not passed to the method, and the property is not a variable and cannot be passed as an out parameter.

ref is there in and out, while out is only out of step.

Excellent is a habit, welcome everyone to pay attention to learning!

Parsing of parameters ref and out in C # methods

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.