ref (C# Reference)
The ref keyword causes arguments to be passed by reference. The effect is that any changes to the parameter in the method will be reflected in that variable when control passes back to the calling method.
To use a ref parameter, both the method definition and the calling method must explicitly use the ref keyword. For example:
An argument passed to a ref parameter must first be initialized. This differs from out, whose arguments do not have to be explicitly initialized before they are passed. For more information, see out.
Although the ref and out keywords cause different run-time behavior, they are not considered part of the method signature at compile time. Therefore, methods cannot be overloaded if the only difference is that one method takes a refargument and the other takes an out argument. The following code, for example, will not compile:
For information about how to pass arrays, see Passing Arrays Using ref and out (C# Programming Guide).
Do not confuse the concept of passing by reference with the concept of reference types. The two concepts are not the same. A method parameter can be modified by ref regardless of whether it is a value type or a reference type. There is no boxing of a value type when it is passed by reference. |
class RefExample { static void Method(ref int i) { // Rest the mouse pointer over i to verify that it is an int. // The following statement would cause a compiler error if i // were boxed as an object. i = i + 44; } static void Main() { int val = 1; Method(ref val); Console.WriteLine(val); // Output: 45 } }
Although the ref and out keywords cause different run-time behavior, they are not considered part of the method signature at compile time. Therefore, methods cannot be overloaded if the only difference is that one method takes a refargument and the other takes an out argument. The following code, for example, will not compile:
Overloading can be done, however, if one method takes a ref or out argument and the other uses neither as in the following example:
Properties are not variables. They are actually methods, and therefore cannot be passed as ref parameters.
For information about how to pass arrays, see Passing Arrays Using ref and out (C# Programming Guide).
Example
Passing value types by reference, as demonstrated earlier in this topic, is useful, but ref is also useful for passing reference types. This allows called methods to modify the object to which the reference refers because the reference itself is being passed by reference. The following sample shows that when a reference type is passed as a ref parameter, the object itself can be changed. For more information, see Passing Reference-Type Parameters (C# Programming Guide).
No comments:
Post a Comment