I'd like to expose a type safe API over a particular JSON format. Here is basically what I have so far:
public class JsonDictionary
{
Dictionary<string, Type> _keyTypes = new Dictionary<string, Type> {
{ "FOO", typeof(int) },
{ "BAR", typeof(string) },
};
IDictionary<string, object> _data;
public JsonDictionary()
{
_data = new Dictionary<string, object>();
}
public void Set<T>(string key, T obj)
{
if (typeof(T) != _keyTypes[key])
throw new Exception($"Invalid type: {typeof(T)} vs {_keyTypes[key]}");
_data[key] = obj;
}
public dynamic Get(string key)
{
var value = _data[key];
if (value.GetType() != _keyTypes[key])
throw new Exception($"Invalid type: {value.GetType()} vs {_keyTypes[key]}");
return value;
}
}
Which can be used nicely as:
JsonDictionary d = new JsonDictionary();
d.Set("FOO", 42);
d.Set("BAR", "value");
However reading the value is a little disapointing and rely on late binding:
var i = d.Get("FOO");
var s = d.Get("BAR");
Assert.Equal(42, i);
Assert.Equal("value", s);
Is there some C# magic that I can use to implement a type-safe generic Get<T>
instead of relying on dynamic
here (ideally type should be checked at compilation time) ? I'd like to also use the pattern for Set<T>
so that d.Set("BAR", 56);
triggers a compilation warning.
Dictionary<string, Type> _keyTypes
can be made static
if needed. The above is just work in progress.