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#?
My order of preference is a solution consisting of general patterns/principles compatible with
that
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 expressing mutability intent through interfaces (where both clients that shouldn't change something and may want to change something can only do so through interfaces, and not the backing class (yes, I know this isn't true immutability, but sufficient):
public interface IX { int Y{ get; } ReadOnlyCollection<string> Z { get; } IMutableX Clone(); } public interface IMutableX: IX { new int Y{ get; set; } new ICollection<string> Z{ get; } // or IList<string> } // generally no one should get ahold of an X directly internal class X: IMutableX { public int Y{ get; set; } ICollection<string> IMutableX.Z { get { return z; } } public ReadOnlyCollection<string> Z { get { return new ReadOnlyCollection<string>(z); } } public IMutableX Clone() { var c = MemberwiseClone(); c.z = new List<string>(z); return c; } private IList<string> z = new List<string>(); } // ... public void ContriveExample(IX x) { if (x.Y != 3 || x.Z.Count < 10) return; var c= x.Clone(); c.Y++; c.Z.Clear(); c.Z.Add("Bye, off to another thread"); // ... }
Would the better solution be to just use F# where you want true immutability?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With