This is more of an academic inquiry than a practical question. Are there any language or framework features that can, or will in future, allow a heterogeneous typed dcitionary, e.g.
myDict.Add("Name", "Bill");
myDict.Add("Height", 1.2);
where myDict now contains not two object
types as values, but one string
and one double
? I could then retrieve my double
with
double dbl = myDict["Height"];
and expect a double or an exception to be thrown?
Please note: The Name and Height values are not necessarily of the same object.
The only way you'll be able to do this if you have a custom collection with generic overloads for Add and Get methods. But that would mean you can ask for the wrong type when reading the key out, so it doesn't gain you much (if anything) over doing the cast yourself when you call your Get method.
However, if you can push the generic type into the key then that could work. Something like (untested code here)
sealed class MyDictionaryKey<T>
{
}
class MyDictionary
{
private Dictionary<object, object> dictionary = new Dictionary<object, object>();
public void Add<T>(MyDictionaryKey<T> key, T value)
{
dictionary.Add(key, value);
}
public bool TryGetValue<T>(MyDictionaryKey<T> key, out T value)
{
object objValue;
if (dictionary.TryGetValue(key, out objValue))
{
value = (T)objValue;
return true;
}
value = default(T);
return false;
}
public T Get<T>(MyDictionaryKey<T> key)
{
T value;
if (!TryGetValue(key, out value))
throw new KeyNotFoundException();
return value;
}
}
Then you can define your keys like:
static readonly MyDictionaryKey<string> NameKey = new MyDictionaryKey<string>();
static readonly MyDictionaryKey<double> HeightKey = new MyDictionaryKey<double>();
and use it like
var myDict = new MyDictionary();
myDict.Add(NameKey, "Bill"); // this will take a string
myDict.Add(HeightKey , 1.2); // this will take a double
string name = myDict.Get(NameKey); // will return a string
double height = myDict.Get(HeightKey); // will return a double
You can use Generic Dictionary<object, object>
; object type for key and object type for value. C# could help.
The keys are all strings? then Dictionary<string,object>
would probably do the job... but when getting values out, you would either need to use object
, or you'd need to cast:
double dbl = (double)myDict["Height"];
object height = myDict["Height"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With