out parameter:
The out keyword passes parameters by reference. The out keyword must be used when defining and calling methods
Simply put, out can be used to return multiple parameter types.
static void Main(string[] args) { string s = "123"; int result; bool b = MyTest(s,out result); } public static bool MyTest(string s, out int result) { bool isTrue; try { result = Convert.ToInt32(s);//Using the out parameter must be assigned within the defined method isTrue = true; } catch { isTrue = false; result = 0; } return isTrue; }
The return type of the method is bool type, and the result variable of int type is returned along with the return of bool type. That is, two variable types are returned.
ref parameter
The ref parameter processes the defined method and returns the result. There is no need for redundant return types to define the method.
The difference between ref parameter and out is that out must be assigned within the defined method, and ref must be assigned to its parameter before calling the method.
static void Main(string[] args) { //Use ref Parameter to exchange the values of two numbers int a = 1; int b = 2; Change(ref a, ref b); Console.WriteLine("a{0},b{1}",a,b); Console.ReadKey(); } public static void Change(ref int a, ref int b) { int temp; temp = a; a = b; b = temp; }
Note that there is no need to return a value when defining a method~
params variable parameters
The elements in the argument list consistent with the variable parameter array type are treated as the elements of the array.
params variable parameter must be the last element of a parameter.
static void Main(string[] args) { //Method 1: you can use array to pass parameters //int[] scores = {22,11,33}; //test("Zhang San",11,scores) //Method 2: you can also directly use elements of the same array type when calling test ("Zhang San", 100, 22, 11, 33); Console.ReadKey(); } /// <summary> /// params Test function to calculate a student's total score /// stay params When using it, you must put it in the last parameter, as shown below! /// </summary> /// <param name="name">Full name</param> /// <param name="number">Student ID</param> /// <param name="s">Variable array score</param> public static void test(string name, int number, params int[] s) { int sum = 0; for (int i = 0; i < s.Length; i++) { sum = sum + s[i]; } Console.WriteLine("{0}The student number of is{1},The total score is{2}", name, number, sum); }