Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is a "mostly complete" (im)mutability approach for C#?
    text
    copied!<p>Since immutability is not fully baked into C# to the degree it is for F#, or fully into the framework (BCL) despite some support in the CLR, what's a fairly complete solution for (im)mutability for C#?</p> <p>My order of preference is a solution consisting of general patterns/principles compatible with</p> <ul> <li>a single open-source library with few dependencies</li> <li>a small number of complementary/compatible open-source libraries</li> <li>something commercial</li> </ul> <p>that</p> <ul> <li>covers Lippert's kinds of <a href="http://blogs.msdn.com/b/ericlippert/archive/2007/11/13/immutability-in-c-part-one-kinds-of-immutability.aspx" rel="nofollow noreferrer">immutability</a></li> <li>offers decent performance (that's vague I know)</li> <li>supports serialization</li> <li>supports cloning/copying (deep/shallow/partial?)</li> <li>feels natural in scenarios such as DDD, builder patterns, configuration, and threading</li> <li>provides immutable collections</li> </ul> <p>I'd also like to include patterns you as the community might come up with that don't exactly fit in a framework such as <a href="https://stackoverflow.com/questions/4310963/best-way-to-separate-read-and-write-concerns-using-interfaces/4311051#4311051">expressing mutability intent through interfaces</a> (where both clients that <em>shouldn't</em> change something and <em>may want to</em> change something can only do so through interfaces, and not the backing class (yes, I know this isn't true immutability, but sufficient):</p> <pre><code>public interface IX { int Y{ get; } ReadOnlyCollection&lt;string&gt; Z { get; } IMutableX Clone(); } public interface IMutableX: IX { new int Y{ get; set; } new ICollection&lt;string&gt; Z{ get; } // or IList&lt;string&gt; } // generally no one should get ahold of an X directly internal class X: IMutableX { public int Y{ get; set; } ICollection&lt;string&gt; IMutableX.Z { get { return z; } } public ReadOnlyCollection&lt;string&gt; Z { get { return new ReadOnlyCollection&lt;string&gt;(z); } } public IMutableX Clone() { var c = MemberwiseClone(); c.z = new List&lt;string&gt;(z); return c; } private IList&lt;string&gt; z = new List&lt;string&gt;(); } // ... public void ContriveExample(IX x) { if (x.Y != 3 || x.Z.Count &lt; 10) return; var c= x.Clone(); c.Y++; c.Z.Clear(); c.Z.Add("Bye, off to another thread"); // ... } </code></pre>
 

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