Note that there are some explanatory texts on larger screens.

plurals
  1. POEncapsulation of reference types inside a collection
    primarykey
    data
    text
    <p>I declared a class with several properties </p> <pre><code>class Soil { public double AnglePhi { get; set; } public double AngleDelta { get; set; } . . . } </code></pre> <p>Now to manipulate a collection of them I built another dedicated class, only for this reason. </p> <pre><code>class Soils { private const Byte numberOPredefined = 10; private IList&lt;Soil&gt; soils; public Soil this[ushort i] { get { return new Soil() { AngleDelta = soils[i].AngleDelta, ... }; } set { if (i &gt; numberOPredefined) soils[i] = value; } } . . . } </code></pre> <p>The logic behind this, is to protect somewhat from direct manipulation of the properties of each Soil instance. Give a copy in getter, ask for a "whole" soil object in setter.</p> <p>From what I red thus far, other solutions could be:<br> make Soil class immutable,<br> return a ReadOnly List (but then the reference types inseide can be manipulated)<br> turn Soil class to struct (simple),<br> augment Soil class with some logic (methods etc). </p> <p>I would like to ask if the above "solution" has any value at all, or is ill-defined. </p> <p>This is a typical situation I think, eg having a <strong>collection of reference types and want to encapsulate them</strong>. What is the typical frame of thinking in these situations ? </p> <p><strong>EDIT :</strong><br> Ok, after reading the answers I modified the solution to this</p> <pre><code>class Soil { private readonly double _AnglePhi; public double AnglePhi { get { return _AnglePhi; } } private readonly double _AngleDelta; public double AngleDelta { get { return _AngleDelta; } } . . } class SoilCollection { private List&lt;Soil&gt; _Soils; public IList&lt;Soil&gt; Soils { get { return _Soils.AsReadOnly(); } } . . } </code></pre> <p>I think the Soil class needed logic inside it, and not inside <em>another</em> class. I 'll post if I find any shortcomings.</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.
 

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