Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><code>AddSomeNodes</code> is not creating an instance of <code>List&lt;TreeNode&gt;</code> because that syntax is a collection initializer (therefore it is not assigning to <code>Nodes</code> meaning it doesn't break the <code>readonly</code> contract), the compiler actually translates the collection initializer into calls to <code>.Add</code>.</p> <p>The <code>AddSomeOtherNodes</code> call actually tries to re-assign the value, but it is <code>readonly</code>. This is also the object initializer syntax, which translates into simple property calls. This property does not have a setter, so that call generates a compiler error. Attempting to add a setter that sets the readonly value will generate another compiler error because it is marked <code>readonly</code>.</p> <p><a href="http://msdn.microsoft.com/en-us/library/bb384062.aspx" rel="nofollow">From MSDN</a>:</p> <blockquote> <p>By using a collection initializer you do not have to specify multiple calls to the Add method of the class in your source code; the compiler adds the calls.</p> </blockquote> <p>Also, just to clarify, there are <strong><em>no</em></strong> anonymous types in play in your code - it is all initializer syntax.</p> <p><hr/> Unrelated to your question, but in the same area.</p> <p>Interestingly, the <code>Nodes = { new TreeNode() }</code> syntax doesn't work with a local member, it only seems to work when it is nested inside an object initializer or during object assignment:</p> <pre><code>List&lt;int&gt; numbers = { 1, 2, 3, 4 }; // This isn't valid. List&lt;int&gt; numbers = new List&lt;int&gt; { 1, 2, 3, 4 }; // Valid. // This is valid, but will NullReferenceException on Numbers // if NumberContainer doesn't "new" the list internally. var container = new NumberContainer() { Numbers = { 1, 2, 3, 4 } }; </code></pre> <p>The MSDN documentation doesn't seem to have any clarification on this.</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. 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