Home > Article > Backend Development > Sample code sharing of c#ref keyword
C# Language Reference
ref (C# Reference)
ref keyword causes parameters to be passed by reference. The effect is that any changes made to the parameters in the method will be reflected in the variable when control is passed back to the calling method. To use ref parameters, both the method definition and the method call must explicitly use the ref keyword. For example:
Copy code
class RefExample { static void Method(ref int i) { i = 44; } static void Main() { int val = 0; Method(ref val); // val is now 44 } }
The parameters passed to the ref parameter must be initialized first. This is different from out , whose parameters do not need to be explicitly initialized before being passed. (See out.)
Although ref and out are handled differently at runtime, they are handled the same way at compile time. Therefore, if one method takes a ref parameter and another method takes an out parameter, both methods cannot be overloaded. For example, from a compilation perspective, the two methods in the following code are identical, so the following code will not compile:
Copy Code
class CS0663_Example { // compiler error CS0663: "cannot define overloaded // methods that differ only on ref and out" public void SampleMethod(ref int i) { } public void SampleMethod(out int i) { } }
However, if a method takes ref or out parameters, and another method does not use these two types of parameters, it can be overloaded, as shown below:
Copy code
class RefOutOverloadExample { public void SampleMethod(int i) { } public void SampleMethod(ref int i) { } }
Remarks
Attributes are not variables and therefore cannot be passed as ref parameters.
For information about passing arrays, see
Passing arrays using ref and out.
Example
It is useful to pass value types by reference (shown above), but ref is also useful for passing reference types. This allows the called method to modify the object referenced by the reference, since the reference itself is passed by reference. The following example shows that when a reference type is passed as the ref parameter, the object itself can be changed.
class RefRefExample { static void Method(ref string s) { s = "changed"; } static void Main() { string str = "original"; Method(ref str); // str is now "changed" } }
The above is the detailed content of Sample code sharing of c#ref keyword. For more information, please follow other related articles on the PHP Chinese website!