C# method (full article – includes: keyword of parameters, method call order, method stack frame and recursive call to realize Fibonacci sequence, etc.)

Directory

1. Basic definition:

1. The basic composition of the method:

2. Basic classification of methods;

2. The use of methods (design and call)

3.var (variable variable) and named parameters

var:

Named parameters:

4. Variable scope in the method

Five. Parameter keywords

1.params parameters (variable parameters)

2.out parameter (output parameter)

3.ref (pass by reference)

6. Passing by value and passing by reference

Seven. Method call sequence

1. When multiple methods are called and the methods are not directly connected

2. Call multiple methods, when the methods are connected (nested)

8. The stack frame of the method

Nine. Recursive call of the method

10. Fibonacci sequence


One. Basic definition:

Functions in a class are called methods, also known as behaviors;

1. The basic composition of the method:

(1) Method modifiers: public and static;

(2) Return value: void has no return value, if there is a return value, it needs to cooperate with return;

(3) Method name: naming rules: big hump;

(4) Formal parameter list: Formal parameters are formal parameters, and actual parameters will be used to pass formal parameters in the future; () are method formal parameters, and formal parameters are not fixed.

(5) Method body: in {};

[public] [static] return type method name([parameter list])
{
method body
}

2. Basic classification of methods;

static method, instance method, parameterless method, parameterized method

Static method: use static, only exists in the class itself, can only be accessed through the class itself, and cannot be accessed through the instance, that is, individual implementation; such as:

public static void Add(int a,int b){}

Instance method: A method that is not modified with a static modifier must be implemented by the individual of the class;

No parameter method: means there is no value in ();

public void Add(){}

Method with parameters: means there is a value in ();

public void Add(int a,int b){}

2. The use of methods (design and call)

1. Method: when the return value is void, return is not required;

public void Add(int a,int b)
        {
            result = a + b;
            Console. WriteLine(result);
        }

Output: At this point, you only need to pass parameters to call the method

var clac=new Clac();//Instantiation
clac.Add(10,20);//Call the method, Add(10,20) is a parameter
//Called in this class, no need to instantiate, just call the method directly

2. When the return value is a basic data type, return is required;

public float Add(float a,float b) {
        return a + b;
        }

Output: Because there is a return value at this time, it needs to be output and printed

var res = clac.Add(12.5f,25.3f);
Console. WriteLine(res);
// can also be abbreviated
Console.WriteLine(clac.Add(12.5f, 25.3f));

3. The type of the return value of a method can be different from the type of the formal parameter;

public string Add(float a, float b, float c)
        {
        return (a + b + c).ToString();//TOstring to string type
        }

three.var (variable variable) and named parameters

var:

In C#, the original definition of variables requires basic data types. Now C# provides a keyword var (variable variable), which is specially used to define variables. The variables it defines do not need to specify the type, and the variable will be inferred according to the value of the variable. 】,like:

var a = 10;

Named parameter:

The type of the actual parameter and the formal parameter of the method must be highly consistent, and the order of delivery must also be highly consistent; if the developer passes the actual parameter in real time, it is not consistent with the formal parameter, and wants the code to execute successfully, what should I do?

Answer: Give the actual parameter an alias; named parameters allow developers to specify the delivery location for the actual parameter

 public static int Add(int a,int b)
        {
            Console.WriteLine($"a value: {a}, b value {b}, result {a + b}");
            return a + b;
        }
// output
Clc.Add(20,10);
Clc.Add(b:20,a:10);
//Output results: the value of a: 20, the value of b is 10, and the result is 30
// The value of a: 10, the value of b is 20, the result is 30

Four. Variable scope in method

The scope refers to the current method. For example, if you want to use a variable in multiple methods, you need to expand the scope of this variable. How to expand it? It can be defined in the class (note: the variables at this time are the same as the variables in the method, but they are not the same). like:

public class Calc
    {
         int result;//Extended to class scope
        public int Add(int a, int b)
        
            result = a + b;//This variable is not the same as the external variable return
            return result;
        }
        public void Fun1()
        {
            //result variable must be defined in the current context to be used
            Console.WriteLine(result);//If you want to use the result, you need to extend the extension, and the external return is called here
        }
        
    }
//transfer
var clc = new Calc();
clc.Fun1(); //result: 0 return has not yet returned the external return
var res = clc. Add(10, 20);
Console.WriteLine(res); //result: 30
clc.Fun1(); //result: 30

5. Parameter keyword

1.params parameter (variable parameter)

Varargs syntax requires:
1. Use the patams keyword to identify that this parameter is a variable parameter
2. The variable parameter must be the last formal parameter of the method;
3. Variable parameters do not mean that the type is variable, but that the number is variable

public void Add2(params int[] arr)
{
   Console.WriteLine($"index{arr[0]}, index{arr[1]}, index{arr[2]}, index{arr[3]}");
        }
// output:
MyClass myClass = new MyClass(); // instance
var arr = new int[] { 0,1, 2, 3 }; //Pass parameters to the formal parameter group
myClass.Add2(arr);

2.out parameter (output parameter)

  1. It can help us return multiple values in one method, regardless of type.
  2. When using the out parameter, it is required that the out parameter must be assigned a value in the method, that is, initialization.
 public void Add3(int a,out int b)
        {
            b = a + 10;
            //Before b wants to get b when calling Add3, it needs to use return;
            // Now you can also use out to transfer parameters to achieve the same effect as return
        }
// output:
int res3 = 0; //Define the initial value first,
myClass.Add3(1,out res3);//Enter the method body, get b as 11, and give res3 at the beginning of the output
Console. WriteLine(res3);

3.ref (pass by reference)

Modifying the ref parameter in the method will affect the external variable

 public void Add4(int a,ref int b)
        {
            a = 20;
            b = 10;
            Console.WriteLine($"The value of internal a is {a}, the value of internal b is {b}");
        }
// output:
a = 200; //Pass to formal parameter first
int b = 100;//Pass to formal parameter first
myClass.Add4(a,ref b);
Console.WriteLine($"External a value {a}, external b value {b}");
//result:
//The value of inner a is 20, the value of inner b is 10
//The value of outer a is 200, the value of outer b is 10

Summary: ref and out values must be assignable variables, that is to say, they need to be initialized

6. Passing by value and passing by reference

Value transfer: the formal parameters are modified in the method, and the external actual parameters are not affected;

Transfer by reference: the formal parameter is modified in the method, which affects the external actual parameter;

What are the pass-by-value?

Answer: 1. Basic data types belong to value transfer

2. Value transfer of string type:

Directly use the string type to pass, and there is no borrowed class call, which is equivalent to redefining the parameters, which will generate a new memory space, so the address of the actual parameter will not change; that is, the string will generate a new address;

Assume that the actual parameter is name, x formal parameter name2; then the actual parameter is passed to the formal parameter at the beginning: name2=name (same address),

But in the method, a new address is generated for name2=”Xiaobai”, so the address of name2 is also changed

What are pass by reference?

Answer: 1. Add the keyword ref before the data type; ref before the data type indicates that the transferred data is a reference type, which is an address;

2. Pass by reference of string type:

When borrowing an instance of a class, no new internal training address is generated when modifying attributes

During class loading, add the string to the string constant pool, and then add the string to determine whether the string content exists in the pool. If it exists, no memory space will be allocated, so the address will change.

string str=null; If it is empty, no memory space will be allocated;

string str=” “; indicates that a position is occupied, so the address will be allocated

Seven. Method call order

1. When multiple methods are called and the methods are not directly connected

1. The order of code execution, the default is from top to bottom () according to the calling order, first execute Fun1, then execute Fun2;

2. When the code encounters a method encapsulated by the developer, it will enter the method body for execution, the star will end, and return to the calling method; if the code encounters a method not encapsulated by the developer, but a method provided by the built-in class library of C#, this Time does not enter the method body.
Reason: The method source code provided by the class library is hidden;

var class1 = new Class1();
class1.Fun1(); //In Fun1() in Class1, after the method body is executed, it will return to this line of code;
class1.Fun2();//Fun1.Fun2 is the method name
//Method nested call There is a connection between these methods
        public void Fun3()
        {
            Console.WriteLine("I am fun3");
            Console.WriteLine("I am fun3.1");
            Fun4();
        }
        public void Fun4()
        {
            Console.WriteLine("I am fun4");
            Console.WriteLine("I am fun4.1");
            Fun5();
        }
        public void Fun5()
        {
            Console.WriteLine("I am fun5");
            Console.WriteLine("I am fun5.1");
        }
//transfer:
class1. Fun3();
//Result: I am fun3
//I am fun3.1
//I am fun4
//I am fun4.1
//I am fun5
//I am fun5.1

Note: Here comes the key point

After reading the output results, do you feel that the call sequence is to execute Fun3 first, then execute Fun4, and then execute Fun5 (wrong sequence), but it is not.

The real sequence can be judged by the breakpoint: F3 (not finished) – F4 (not finished) – F5 (one-time finished) – F4 (finished) – F3 (finished)

Entry order: method nesting order F3-F4-F5; execution order: F3-F4-F5 execution completion order: F5-F4-F); first in last out

Eight. Method stack frame

The stack frame of the method call: it is the memory space allocated to the method when the method is executed;
When the method is executed, as long as the memory space is allocated and the method is called, it will enter this memory space. The memory space execution sequence is called “call stack”;
The call stack is actually first-in, last-out. I call the execution sequence of this stack frame: a U-shaped structure;

9. Recursive call of method

In a method, call the method itself, in short: call yourself
Recursion has a self-loop. Be careful with recursion: there must be an exit (the method can stop). If there is no exit for recursion, it will enter an “infinite loop” and a stack overflow error will occur;

Code demo:

private int count = 3;
        public void Count() {
        Console.WriteLine($"Currently: {count}");
            if (count-- == 0)
            {
                return;
            }
            Count();//Call yourself
        }
//transfer:
class1. Count();
/*Output result: currently: 3
            Current is: 2
            Current is: 1
            Currently: 0 */

Ten. Fibonacci sequence (Fibonacci sequence)

The Fibonacci sequence, also known as the golden section sequence, was introduced by the mathematician Leonardo Fibonacci with the example of rabbit breeding, so it is also called the “rabbit sequence”. What is more is such a sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34, … In mathematics, the Fibonacci sequence is defined recursively as follows: F(0)= 0, F(1)=1, F(n)=F(n – 1) + F(n – 2) (n ≥ 2, n ∈ N*)
Code demo:

public int Fib(int n)
        {
            if (n == 0)
            {
                return 0;
            }
            else if (n == 1)
            {
                return 1;
            }
            else
            {
            return Fib(n-1) + Fib(n-2);
            }
        }
// output:
Console.WriteLine(class1.Fib(0));
Console. WriteLine(class1. Fib(1));
Console. WriteLine(class1. Fib(2));
Console. WriteLine(class1. Fib(3));
Console. WriteLine(class1. Fib(4));
Console.WriteLine(class1.Fib(5));
//Result: 0 1 1 2 3 5