Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>To better demonstrate the properties of <code>readonly</code>:</p> <pre><code>order.Product = Product.Create("Apple") // &lt;- not allowed because Product field is readonly order.Product.Name = "Apple" // &lt;- allowed because Name is not readonly field or private property </code></pre> <p>After making setter of property Name private (e.g. <code>public string Name { get; private set; }</code>):</p> <pre><code>order.Product.Name = "Apple" // &lt;- not allowed </code></pre> <p>The problem with this solution, of course is:</p> <pre><code>new Product { Name = "Orange" } // &lt;- not allowed if called from outside Product class </code></pre> <p>You have 2 options:</p> <ul> <li>if you don't want any properties of Product be modifiable (e.g. be immutable) then simply don't define setters (or make setters private) and have constructor (or factory method) of Product initialize them</li> <li>if you still want properties of Product be modifiable but not when it's a member of Order then create an interface IProduct with property Name defined as: <code>public string Name { get; }</code>, make Product implement this interface, and then make Product field of type Order defined as: <code>public readonly IProduct Product;</code></li> </ul> <p>Any of this solutions will achieve both of your requirements:</p> <pre><code>order.Product.Name = "Apple" // &lt;- not allowed new Product { Name = "Orange" } // &lt;- allowed when called from Product's Create method </code></pre> <p>With only difference between them:</p> <pre><code>order.Product.Name = "Apple" // &lt;- not allowed Product product = new Product { Name = "Orange" } // not allowed in solution #1 when called from outside Product, allowed in solution #2 product.Name = "Apple" // &lt;- not allowed in solution #1 but allowed in solution #2 </code></pre>
    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. This table or related slice is empty.
    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