expandoobjectexpandokephas

Is there a possibility to control the Expando class to not allow adding properties/members under certain conditions?


As far as I can tell, the Expando class in Kephas allows adding new members on the fly. Unlike the ExpandoObject in .NET, I noticed it is not sealed, so I could change its behavior, but I don't really know how.

[EDITED]

My scenario is to make the expando readonly at a certain time.


Solution

  • Try this snippet:

    public class ReadOnlyExpando : Expando
    {
        private bool isReadOnly;
    
        public ReadOnlyExpando()
        {
        }
    
        public ReadOnlyExpando(IDictionary<string, object> dictionary)
            : base(dictionary)
        {
        }
    
        public void MakeReadOnly()
        {
            this.isReadOnly = true;
        }
    
        protected override bool TrySetValue(string key, object value)
        {
            if (this.isReadOnly)
            {
                throw new InvalidOperationException("This object is read only").
            }
    
            return base.TrySetValue(key, value);
        }
    }
    

    For other scenarios you may want to check the LazyExpando class, which provides a way to resolve dynamic values based on a function, also handling circular references exception.