6.2.2 parameters and return values with global data
This section details how to exchange data with functions through global data and parameters and return values. First look at the following code:
classProgram {Static voidShowdouble (ref intval) {Val*=2; Console.WriteLine ("val doubled = {0}", Val); } Static voidMain (string[] args) { intval =5; Console.WriteLine ("val = {0}", Val); Showdouble (refval); Console.WriteLine ("val = {0}", Val); } }
Compare with the following code:
classProgram {Static intVal; Static voidshowdouble () {Val*=2; Console.WriteLine ("val doubled = {0}", Val); } Static voidMain (string[] args) {Val=5; Console.WriteLine ("val = {0}", Val); Showdouble (); Console.WriteLine ("val = {0}", Val); } }
The results of these two showdouble () functions are the same.
First, in the first discussion of this issue, the showdouble () version using global values only uses the global variable val. In order to use this version, it is necessary to use this global variable. This can have a slight limitation on the diversity of the function, and if you want to store the result, you must always copy the global variable value into other variables. In addition, the global data can be modified by the code elsewhere in the application, which results in unexpected outcomes (whose values may change, which is too late when we realize this).
However, the loss of diversity is often beneficial. We often want a function to be used only for one purpose, using global data storage to reduce the likelihood of making a mistake in a function call, such as passing it to the wrong variable.
Of course, it can also be said that this simplification actually makes the code more difficult to understand. Explicitly specifying parameters can see what has changed at a glance. such as functionname (Val1, out val2) function calls, where val1 and val2 are important variables to consider, at the end of the function execution, VAL2 is fully assigned a new value. Conversely, if the function does not have parameters, it cannot manipulate what data it has.
In short, you have the freedom to choose which technology to use to exchange data. In general, it is best to use parameters rather than global data, but sometimes it is more appropriate to use global data, and there is no mistake in using this technique.
(original) C # learning note 06--function 02--variable scope 02--parameter and return value with global data