In C #, if the ref keyword is added before the method parameter, it indicates that the parameter is passed as a reference, not a value. How can this problem be understood?
Parameters are simple type examples
static void Main(string[] args) { string temp = "a"; Change(temp); Console.WriteLine(temp); ChangeByRef(ref temp); Console.WriteLine(temp); Console.ReadKey(); } private static void Change(string temp) { temp = temp + "--changed"; } private static void ChangeByRef(ref string temp) { temp = temp + "--refchanged"; }
Output result:
A
A -- refchanged
● In the change () method, although the Temp value is changed, the method does not return a value. Printing temp is still the initial value;
● In the chnagebyref () method, the reference address of temp is changed after the Temp value is changed because the keyword is added and no return value is returned. Print it again, the temp value is the value corresponding to the new reference address.
Example of a parameter as a class type
Class program {static void main (string [] ARGs) {pet P = new pet () {age = 5}; console. writeline ("initial age: {0}", p. age); changeage (p); console. writeline ("after changing the pet property value, age is: {0}", p. age); changeagebyref (ref P); console. writeline ("after the pet reference address is changed, the age is: {0}", p. age); console. readkey ();} Private Static void changeage (PET p) {P. age = 10;} Private Static void changeagebyref (ref pet p) {P = new pet () {age = 20 }}} public class pet {public int age {Get; set ;}}
Output result:
● In the changeage () method, the property value of the pet instance is changed.
● In the changeagebyref () method, change the reference address of the pet instance.
Summary
Whether it is a simple type or a class type, if the ref keyword is added before the method parameter, the parameter value changes the reference address of the method parameter variable. Note:
● Before using a method with Ref, you must assign an initial value to the method variable.
● The keyword ref must be included in both defining methods and using methods.