1. Define and use functions.
Let's explain it through examples.
ClassProgram {Static VoidWrite () {console. writeline ("Test output from Function");}Static VoidMain (String[] ARGs) {write (); console. readkey ();}}
1. function architecture
(1) KEYWORDS: static and void
Static has a relationship with object-oriented thinking. We need to add this keyword to each function by default here;
Void indicates that the return value is null. ,
(2) function name followed by parentheses e. g write ();
(3) There can be parameters in parentheses, which will be discussed later,
(4) A code block to be executed is placed in curly brackets.
2. Return Value
(1) When a function returns a value, you can modify the function in either of the following ways:
A. Specify the return value type in the function declaration, but do not use the keyword void;
B. Use the return keyword to end function execution and send the return value to the calling code.
Static<Returntype> <functionname>(){......Return<Returnvalue>;}
(2) return does not have to be placed in the last row, and is often used to directly jump out of the function.
3. Parameters
(1) When the function accepts parameters, you must specify the following content:
A. In its definition, the function specifies the list of accepted parameters, and the type of these parameters;
B. List of parameters matched in each function call.
C. There can be any number of parameters. Each parameter has a type and a name. The parameters are separated by commas. Each parameter is used as a variable in the function code.
(2) A demo
Namespace Exercise { Class Program { Static Int Maxvalue ( Int [] Intarray ){ Int Maxval = intarray [ 0 ]; For ( Int I = 1 ; I <intarray. length; I ++ ){ If (Intarray [I]> Maxval) {maxval = Intarray [I] ;}} Return Maxval ;} Static Void Main ( String [] ARGs ){ Int [] Myarray = { 1 , 5 , 7 ,99 , 7 , 8 , 9 , 3 }; Int Maxval = Maxvalue (myarray); console. writeline ( " The maximum value in myarray is {0} " , Maxval); console. readkey ();}}}
The running result is:
(3) Parameter Matching
C # Study Notes (5) -- Functions