Skip to content

Instantly share code, notes, and snippets.

@kkurni
Last active January 1, 2016 23:09
Show Gist options
  • Save kkurni/8214959 to your computer and use it in GitHub Desktop.
Save kkurni/8214959 to your computer and use it in GitHub Desktop.
This is Dynamic custom model t which useful to create object graph where you want your object to be very flexible such as in razor template use cases
public class DynamicModel : DynamicObject
{
private readonly bool _isStrictGet;
public IDictionary<string, object> _dict;
public DynamicModel(string objectName = null, IDictionary<string, object> dict = null, bool isStrictGet = false)
{
ObjectName = objectName;
_dict = dict ?? new Dictionary<string, object>();
_isStrictGet = isStrictGet;
}
#region <<Override method>>
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (_dict.ContainsKey(binder.Name))
{
result = _dict[binder.Name];
return true;
}
//if it can't find any keys
if (_isStrictGet)
{
//if you need to be
result = null;
return false;
}
//to make this to return gracefully you can set this to true so that it will return empty string.
result = new DynamicModel("");
return true;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
Add(binder.Name, value);
return true;
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _dict.Keys;
}
public override string ToString()
{
return ObjectName ?? base.ToString();
}
#endregion
#region <<helper method>>
public void Add(string key, object value)
{
if (_dict.ContainsKey(key))
{
_dict[key] = value;
}
else
{
_dict.Add(key, value);
}
}
public bool ContainsKey(string key)
{
return _dict.ContainsKey(key);
}
public object GetValue(string key)
{
return _dict.ContainsKey(key) ? _dict[key] : null;
}
#endregion
public string ObjectName { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment