C# DictionaryModel

Date: 2019-12-20

For extending JSON or dynamic types with optional fields

public class DictionaryModel
{
	private Dictionary<string, object> _data = new Dictionary<string, object>();
	public void SetDictionary(Dictionary<string, object> data) 
	{
		_data = data;
	}
	public Dictionary<string, object> GetDictionary() {
		return _data;
	}

	protected T Get<T>(string key, T defaulValue = default(T)) {
		if (_data.TryGetValue(key, out var val)) {
			if (val == null)
				return defaulValue;
			if (val is T)
				return (T)val;

			var basicType = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
			try
			{
				var basicVal = Convert.ChangeType(val, basicType);
				return (T)basicVal;
			}
			catch (Exception)
			{
				//Ignore
			}
		}
		return defaulValue;
	}

	protected void Set(string key, object value) {
		_data[key] = value;
	}
}

public class ModelWithDescription : DictionaryModel
{
	public string Description
	{
		get => Get<string>("Description");
		set => Set("Description", value);
	}
	public int? Quantity
	{
		get => Get<int?>("Quantity");
		set => Set("Quantity", value);
	}
}
30640cookie-checkC# DictionaryModel