1

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.

Auguste Leroi
  • 215
  • 1
  • 7
  • Do you have any particular scenario in mind? There are a lot of possibilities to extend the Expando, so it would be helpful to provide more information about your use case. – ioan Mar 13 '19 at 18:45
  • I just edited the description, hope now my intent is more clear – Auguste Leroi Mar 13 '19 at 19:38

1 Answers1

1

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.

ioan
  • 722
  • 4
  • 12