Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Pass a <code>ref</code> if you want to change what the object is:</p> <pre><code>TestRef t = new TestRef(); t.Something = "Foo"; DoSomething(ref t); void DoSomething(ref TestRef t) { t = new TestRef(); t.Something = "Not just a changed t, but a completely different TestRef object"; } </code></pre> <p>After calling DoSomething, <code>t</code> does not refer to the original <code>new TestRef</code>, but refers to a completely different object.</p> <p>This may be useful too if you want to change the value of an immutable object, e.g. a <code>string</code>. You cannot change the value of a <code>string</code> once it has been created. But by using a <code>ref</code>, you could create a function that changes the string for another one that has a different value.</p> <p>Edit: As other people have mentioned. It is not a good idea to use <code>ref</code> unless it is needed. Using <code>ref</code> gives the method freedom to change the argument for something else, callers of the method will need to be coded to ensure they handle this possibility.</p> <p>Also, when the parameter type is an object, then object variables always act as references to the object. This means that when the <code>ref</code> keyword is used you've got a reference to a reference. This allows you to do things as described in the example given above. But, when the parameter type is a primitive value (e.g. <code>int</code>), then if this parameter is assigned to within the method, the value of the argument that was passed in will be changed after the method returns:</p> <pre><code>int x = 1; Change(ref x); Debug.Assert(x == 5); WillNotChange(x); Debug.Assert(x == 5); // Note: x doesn't become 10 void Change(ref int x) { x = 5; } void WillNotChange(int x) { x = 10; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload