Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Put succinctly, you would pass a value as a <code>ref</code> parameter if you want the function you're calling to be able to alter the value of that variable.</p> <p>This is not the same as passing a reference <em>type</em> as a parameter to a function. In those cases, you're still passing by value, but the value <em>is</em> a reference. In the case of passing by <code>ref</code>, then an actual reference to the variable is sent; essentially, you and the function you're calling "share" the same variable.</p> <p>Consider the following:</p> <pre><code>public void Foo(ref int bar) { bar = 5; } ... int baz = 2; Foo(ref baz); </code></pre> <p>In this case, the <code>baz</code> variable has a value of 5, since it was passed by reference. The semantics are entirely clear for value types, but not as clear for reference types.</p> <pre><code>public class MyClass { public int PropName { get; set; } } public void Foo(MyClass bar) { bar.PropName = 5; } ... MyClass baz = new MyClass(); baz.PropName = 2; Foo(baz); </code></pre> <p>As expected, <code>baz.PropName</code> will be 5, since <code>MyClass</code> is a reference type. But let's do this:</p> <pre><code>public void Foo(MyClass bar) { bar = new MyClass(); bar.PropName = 5; } </code></pre> <p>With the same calling code, <code>baz.PropName</code> will remain 2. This is because even though <code>MyClass</code> is a reference type, <code>Foo</code> has its own variable for <code>bar</code>; <code>bar</code> and <code>baz</code> just start out with the same value, but once <code>Foo</code> assigns a new value, they are just two different variables. If, however, we do this:</p> <pre><code>public void Foo(ref MyClass bar) { bar = new MyClass(); bar.PropName = 5; } ... MyClass baz = new MyClass(); baz.PropName = 2; Foo(ref baz); </code></pre> <p>We'll end up with <code>PropName</code> being 5, since we passed <code>baz</code> by reference, making the two functions "share" the same variable.</p>
 

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