Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Heterogeneous Dictionary, but typed?

Tags:

.net

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.

like image 985
ProfK Avatar asked Nov 27 '08 12:11

ProfK


3 Answers

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
like image 93
Wilka Avatar answered Nov 08 '22 21:11

Wilka


You can use Generic Dictionary<object, object>; object type for key and object type for value. C# could help.

like image 27
Ali Ersöz Avatar answered Nov 08 '22 21:11

Ali Ersöz


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"];
like image 32
Marc Gravell Avatar answered Nov 08 '22 21:11

Marc Gravell