1. Before "Out", "params" and "ref", the most commonly used parameter passing by value is recorded. Of course, by default, the default behavior of parameter passing in to the function is also passed by value.
1: // by default, parameters are passed by value
2: static int add(int x,int y) {
3: int ans = x + y;
4: x = 1000; y = 2000;
5: return ans;
6: }
1: static void Main(string[] args) {
2: Console. WriteLine ("pass by value by default ");
3: int x = 3, y = 8;
4: Console. WriteLine ("before calling: x: {0}, y: {1}", x, y );
5: Console. WriteLine ("result after call: {0}", add (x, y ));
6: Console. WriteLine ("after calling: x: {0}, y: {1}", x, y );
7: Console.ReadLine();
8: }
The output result is as expected:
2. Out Modifier
1: static void add(int x,int y,out int ans) {
2: ans = x + y;
3: }
This can be written in Main:
1: int ans;
2: add(20, 20, out ans);
3: Console.WriteLine("20+20={0}", ans);
4: Console.ReadLine();
Of course, the output result is: 20 + 20 = 40. In the past, if no out is used, "the unassigned local variable is used ".
Even if we assign a value to ans, for example, int ans = 10;
It does not change after calling the add method, because the called method does not know what is going on.
This turns to 20 + 20 = 10, which is obviously wrong.
Of course, the biggest highlight of Out is that multiple parameter values can be output after a function call.
Change the above method:
1: static void setParams(out int x,out string y,out bool ans) {
2: x = 2;
3: y = "YeanJay";
4: ans = true;
5: }
We can write this in Main: