Note that there are some explanatory texts on larger screens.

plurals
  1. POInitializing a Generic.List in C#
    text
    copied!<p>In C#, I can initialize a list using the following syntax.</p> <pre><code>List&lt;int&gt; intList= new List&lt;int&gt;() { 1, 2, 3 }; </code></pre> <p>I would like to know how that <code>{}</code> syntax works, and if it has a name. There is a constructor that takes an <code>IEnumerable</code>, you could call that.</p> <pre><code>List&lt;int&gt; intList= new List&lt;int&gt;(new int[]{ 1, 2, 3 }); </code></pre> <p>That seems more "standard". When I deconstruct the default constructor for the List I only see </p> <pre><code>this._items = Array.Empty; </code></pre> <p>I would like to be able to do this.</p> <pre><code>CustomClass abc = new CustomClass() {1, 2, 3}; </code></pre> <p>And be able to use the <code>1, 2, 3</code> list. How does this work?</p> <p><strong>Update</strong> </p> <p>Jon Skeet answered</p> <blockquote> <p>It's calling the parameterless constructor, and then calling Add:</p> </blockquote> <pre><code>&gt; List&lt;int&gt; tmp = new List&lt;int&gt;(); &gt; tmp.Add(1); tmp.Add(2); tmp.Add(3); &gt; List&lt;int&gt; intList = tmp; </code></pre> <p>I understand what is does. I want to know how. How does that syntax know to call the Add method? </p> <p><strong>Update</strong></p> <p>I know, how cliche to accept a Jon Skeet answer. But, the example with the strings and ints is awesome. Also a very helpful MSDN page is:</p> <ul> <li><em><a href="http://msdn.microsoft.com/en-us/library/bb384062.aspx" rel="noreferrer">Object and Collection Initializers (C# Programming Guide)</a></em></li> </ul>
 

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