Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Object Initializers were something added to C# 3, in order to simplify construction of objects when you're using an object.</p> <p>Constructors run, given 0 or more parameters, and are used to create and initialize an object <em>before</em> the calling method gets the handle to the created object. For example:</p> <pre class="lang-cs prettyprint-override"><code>MyObject myObjectInstance = new MyObject(param1, param2); </code></pre> <p>In this case, the constructor of <code>MyObject</code> will be run with the values <code>param1</code> and <code>param2</code>. These are both used to create the new <code>MyObject</code> in memory. The created object (which is setup using those parameters) gets returned, and set to <code>myObjectInstance</code>.</p> <p>In general, it's considered good practice to have a constructor require the parameters needed in order to completely setup an object, so that it's impossible to create an object in an invalid state.</p> <p>However, there are often "extra" properties that could be set, but are not required. This could be handled through overloaded constructors, but leads to having lots of constructors that aren't necessarily useful in the majority of circumstances.</p> <p>This leads to object initializers - An Object Initializer lets you set properties or fields on your object <em>after</em> it's been constructed, but <em>before</em> you can use it by anything else. For example:</p> <pre class="lang-cs prettyprint-override"><code>MyObject myObjectInstance = new MyObject(param1, param2) { MyProperty = someUsefulValue }; </code></pre> <p>This will behave about the same as if you do this:</p> <pre class="lang-cs prettyprint-override"><code>MyObject myObjectInstance = new MyObject(param1, param2); myObjectInstance.MyProperty = someUsefulValue; </code></pre> <p>However, in <em>multi-threaded</em> environments the atomicity of the object initializer may be beneficial, since it prevents the object from being in a not-fully initialized state (see <a href="https://stackoverflow.com/a/12842511/2822719" title="Is there any benefit of using an Object Initializer? - Top answer">this answer</a> for more details) - it's either null or initialized like you intended.</p> <p>Also, object initializers are simpler to read (especially when you set multiple values), so they give you the same benefit as many overloads on the constructor, without the need to have many overloads complicating the API for that class.</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