Are immutable arrays possible in .NET?

后端 未结 9 831
忘了有多久
忘了有多久 2020-12-05 23:22

Is it possible to somehow mark a System.Array as immutable. When put behind a public-get/private-set they can\'t be added to, since it requires re-allocation a

9条回答
  •  旧巷少年郎
    2020-12-05 23:59

    Further to Matt's answer, IList is a complete abstract interface to an array, so it allows add, remove, etc. I'm not sure why Lippert appears to suggest it as an alternative to IEnumerable where immutability is needed. (Edit: because the IList implementation can throw exceptions for those mutating methods, if you like that kind of thing).

    Maybe another thing to bear in mind that the items on the list may also have mutable state. If you really don't want the caller to modify such state, you have some options:

    Make sure the items on the list are immutable (as in your example: string is immutable).

    Return a deep clone of everything, so in that case you could use an array anyway.

    Return an interface that gives readonly access to an item:

    interface IImmutable
    {
        public string ValuableCustomerData { get; }
    }
    
    class Mutable, IImmutable
    {
        public string ValuableCustomerData { get; set; }
    }
    
    public class Immy
    {
        private List _mutableList = new List();
    
        public IEnumerable ImmutableItems
        {
            get { return _mutableList.Cast(); }
        }
    }
    

    Note that every value accessible from the IImmutable interface must itself be immutable (e.g. string), or else be a copy that you make on-the-fly.

提交回复
热议问题