(original) C # learning Note 06--function 01--define and use function 02--parameters

Source: Internet
Author: User

6.1.2 Parameters

When a function accepts a parameter, it must specify the following:

The function specifies in its definition the list of arguments to accept, and the type of these parameters.

A list of parameters that match in each function call.

This involves the following code:

      static <returnType> <FunctionName> (<paramType> <paramName>, ...)       {           ...            return <returnValue>;       }

There can be any number of arguments, each with a type and a name. Parameters are separated by commas. Each parameter is used as a variable in the code of the function.

For example, here is a simple function with two double arguments and returns the product of them:

      Static Double Product (doubledouble  param2)       {           return param1 * param2;       }

Here is an example of the following code:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacech06ex02{classProgram {Static intMaxValue (int[] intarray) {            intMaxval = intarray[0];  for(inti =1; i < intarray.length; ++i) {if(Intarray[i] >maxval) {Maxval=Intarray[i]; }            }            returnMaxval; }        Static voidMain (string[] args) {            int[] MyArray = {1,8,3,5,9,4, $,1,0,1 }; Console.WriteLine ("The maximum value in MyArray is {0}", MaxValue (MyArray));        Console.readkey (); }    }}

1. Parameter matching

When calling a function, you must match the argument exactly with the parameter specified in the function definition, which means that you want to match the type, number, and order of the arguments.

Note: Use the name and parameters of the function to define the signature of the function.

  

2. Array of parameters

C # allows you to specify one (only one) specific parameter for a function, which must be the last parameter in the function definition, called a parameter array. parameter arrays can call functions with variable numbers of parameters, which can be defined using the params keyword.

The parameter array simplifies the code because you do not have to pass the array from the calling code, and you pass several parameters of the same type , which are placed in an array that can be used in the function.

When you define a function that uses a parameter array, you need to use the following code:

      static <returnType> <FunctionName> (<p1Type> <p1name>,...,params <type >[] <name>)       {           ...            return <returnValue>;       }

The function can be called using the following code.

<FunctionName> (<p1>,..., <val1>, <val2>,...)

Where <val1> and <val2> are all <type> type values that are used to initialize the <name> array. The number of parameters you can specify is almost unlimited. The only limitation is that they must all be <type> types. You can even specify no parameters at all.

This makes the parameter array particularly suitable for specifying additional information for functions to be used during processing.

For example, suppose you have a function, Getword (), whose first argument is a string value, and returns the first word in the string.

string FirstWord = Getword ("This isa sentence. "

Where FirstWord is given the string this.

You can add a params parameter in Getword () to select another word to return based on its index:

string FirstWord = Getword ("This isa sentence. " 2

Assuming that the first word count is 1, the FirstWord is given a string is.

It is also possible to limit the number of characters returned in the 3rd parameter, as well as by the params parameter:

string FirstWord = Getword ("This isa sentence. " 4 3

At this point FirstWord is given the string Sen.

The following example defines and uses a function with the params type parameter. The code is as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacech06ex03{classProgram {Static intSumvals (params int[] vals) {            intsum =0; foreach(intValinchVals) {Sum+=Val; }            returnsum; }        Static voidMain (string[] args) {Console.WriteLine ("summed values = {0}", Sumvals (1,5,2,9,8));        Console.readkey (); }    }}

3. Reference parameters and value parameters

All functions defined so far in this chapter have value parameters. The implication is that when using parameters, a value is passed to a variable used by the function. Any modification to this variable in a function does not affect the parameters specified in the function call.

For example, the following function doubles the value of the passed parameter and displays it:

      Static void showdouble (int  val)       {           2;           Console.WriteLine ("val doubled = {0}", Val);       }

The parameter Val is doubled in this function if it is called as follows:

      int 5 ;       Console.WriteLine ("MyNumber = {0}", MyNumber);       Showdouble (MyNumber);       Console.WriteLine ("MyNumber = {0}", MyNumber);

The text output to the console looks like this:

 55

With MyNumber as a parameter, calling showdouble () does not affect the value of MyNumber in main (), even if the parameter given Val is doubled, the value of MyNumber is not changed.

This is good, but if you want to change the value of the MyNumber, there is a problem. You can use a function that returns a new value for MyNumber:

      Static intDoublenum (intval) {Val*=2; returnVal; }      // Use      intMyNumber =5; Console.WriteLine ("MyNumber = {0}", MyNumber); MyNumber=Doublenum (MyNumber); Console.WriteLine ("MyNumber = {0}", MyNumber);

However, this code is not intuitive at all and cannot change the values of multiple variables used as parameters (because the function has only one return value).

Parameters can now be passed by reference. The variable that the function handles is the same as the variable used in the function call, not just the variable with the same value. Therefore, any change to this variable will affect the value of the variable used as a parameter. To do this, simply specify the parameters using the ref keyword :

      Static voidShowdouble (ref intval) {Val*=2; Console.WriteLine ("val doubled = {0}", Val); }      // Use      intMyNumber =5; Console.WriteLine ("MyNumber = {0}", MyNumber); Showdouble (refMyNumber); Console.WriteLine ("MyNumber = {0}", MyNumber);

Output:

       5 ten              

This time, MyNumber was modified by showdouble ().

There are two restrictions on the variables used as ref parameters.

First, the function may change the value of the reference parameter, so a "very variable" (that is, a const variable) must be used in the function call.

Second, you must use the initialized variable.

4 Output parameters

In addition to passing values by reference, you can also use the Out keyword to specify that the given parameter is an output parameter. The Out keyword is used the same way as the ref keyword (the modifier used as a parameter in function definitions and function calls). In fact, it executes exactly the same way as a reference parameter, because the value of the parameter is returned to the variable used in the function call after the function has finished executing. However, there are some important differences:

It is illegal to use an unassigned variable as a ref parameter, but an unassigned variable can be used as an out parameter.

In addition, when a function uses an out parameter, the out parameter must be treated as if it has not been assigned a value. That is, the calling code can use an assigned variable as an out parameter, and the value stored in the variable is lost when the function executes.

For example, consider the MaxValue () function, which returns the largest value in the array, and slightly modify the function to get the element index of the largest value in the array. For simplicity, if the value of more than one element in the array is the maximum value, only the index of the first maximum value is fetched. To do this, modify the function and add an out parameter as follows:

      Static intMaxValue (int[] Intarray, out intMaxindex) {           intMaxval = intarray[0]; Maxindex=0;  for(inti =1; i < intarray.length; i++)           {               if(Intarray[i] >maxval) {Maxval=Intarray[i]; Maxindex=i; }           }           returnMaxval; } 

You can use this function in the following ways:

      int[] MyArray = {1,8,3,6,2,5,9,3,0,2 }; intMaxindex; Console.WriteLine ("The maximum value in MyArray is {0}", MaxValue (MyArray, outmaxindex)); Console.WriteLine ("The first occurrence of this value are at element {0}", Maxindex+1);

The results are as follows:

      inch  is 9 This is7         

Note that you must use the Out keyword in a function call, just like the ref keyword.

  

(original) C # learning Note 06--function 01--define and use function 02--parameters

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.