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.