Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Unless you specify <code>ref</code> or <code>out</code>, parameters are passed by value. For reference types, that means a <em>reference</em> to the object (the <code>List&lt;int&gt;</code> in this case) is passed by value.</p> <p>"Pass by value" means that the <em>argument</em> (the expression in the calling statement) is evaluated, and then the resulting value is copied into the <em>parameter</em> (the variable listed in the method signature). Any further changes to the parameter, in terms of assigning it a new value, are <em>not</em> seen by the caller. (But keep reading...)</p> <p>That means that in your first method call:</p> <pre><code>public static void SampleMethod1(List&lt;int&gt; i) { List&lt;int&gt; j = new List&lt;int&gt;(); j.Insert(0,20); i = j; } </code></pre> <p>you're creating a new list, inserting a value into it, and then copying the reference to that new list to <code>i</code> - but that has <em>no effect at all</em>. The parameter is effectively just another local variable - a change to the value of the variable itself doesn't affect the caller.</p> <p>Now compare that with your second method:</p> <pre><code>public static void SampleMethod2(List&lt;int&gt; i) { List&lt;int&gt; j = new List&lt;int&gt;(); j = i; j.Insert(0, 20); } </code></pre> <p>This creates a new list and then immediately ignores it, instead assigning the reference to the list passed in (as <code>i</code>) to <code>j</code>. It then inserts a value into the list. The net result of this method is that a value is inserted into the list. It's equivalent to:</p> <pre><code>public static void SampleMethod2(List&lt;int&gt; i) { i.Insert(0, 20); } </code></pre> <p>Note that this is <em>not</em> changing the value of the parameter. It's making a change to the object that the value of the parameter refers to. This is a <em>crucial</em> difference to understand.</p> <p>I have an article on <a href="http://pobox.com/~skeet/csharp/parameters.html" rel="noreferrer">parameter passing</a> and another one on <a href="http://pobox.com/~skeet/csharp/references.html" rel="noreferrer">reference and value types</a> which may help you understand this more.</p>
    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. 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.
 

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