C # Language Reference
Ref (C # Reference)
The REF keyword enables parameters to be passed by reference. The effect is that when control is passed back to the calling method, any changes made to the parameter in the method are reflected in the variable. To use the ref parameter, both the method definition and the calling method must explicitly use the REF keyword. For example:
Copy Code
Class refexample{ static void Method (ref int i) { i =; } static void Main () { int val = 0; Method (ref val); Val is now,} }
The arguments passed to the ref parameter must be initialized first. This differs from out in that the out parameter does not need to be explicitly initialized before it is passed. (See out.) )
Although ref and out are handled differently at run time, they are handled identically at compile time. Therefore, if one method takes a ref parameter and the other method takes an out parameter, the two methods cannot be overloaded. For example, from a compilation point of view, the two methods in the following code are identical, so the following code will not be compiled:
Copy Code
Class Cs0663_example { //Compiler Error CS0663: "Cannot define overloaded //methods that differ only in ref an D out "public void SampleMethod (ref int. i) { } public void SampleMethod (out int i) { }}
However, if a method takes a ref or out parameter and the other method does not take these two types of arguments, it can be overloaded as follows:
Copy Code
Class refoutoverloadexample{public void SampleMethod (int. i) { } public void SampleMethod (ref int i) { } }
Note
property is not a variable and therefore cannot be passed as a ref parameter.
For information about passing arrays, see
The array is passed using ref and out.
Example
Passing value types by reference (as shown above) is useful, but ref is also useful for passing reference types. This allows the called method to modify the object referenced by the reference, because the reference itself is passed by reference. The following example shows that the object itself can be changed when the reference type is passed as a ref parameter.
Class refrefexample{ static void Method (ref string s) { s = "changed"; } static void Main () { string str = "original"; Method (ref str); STR is now "changed" }}