Source

RubyCSharp / Dynamic / CSharpDynamic / DynamicFeaturesSamples / DynamicEntity.cs

using System.Collections.Generic;
using System.Dynamic;

namespace DynamicFeaturesSamples
{
    public class DynamicEntity : DynamicObject
    {
        Dictionary<string, object> _additionalData = new Dictionary<string, object>();

        public DynamicEntity(IEnumerable<KeyValuePair<string, object>> additionalData)
        {
            foreach (var keyValuePair in additionalData)
            {
                _additionalData.Add(keyValuePair.Key, keyValuePair.Value);
            }
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (_additionalData.ContainsKey(binder.Name))
            {
                result = _additionalData[binder.Name];
                return true;
            }
            return base.TryGetMember(binder, out result);
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            if (_additionalData.ContainsKey(binder.Name))
            {
                _additionalData[binder.Name] = value;
                return true;
            }

            return base.TrySetMember(binder, value);
        }

        public bool RespondTo(string message)
        {
            return _additionalData.ContainsKey(message);
        }
    }
}