Search code examples
c#castingkeyvaluepair

Cast object to KeyValuePair with "generic value"?


I have a ComboBox filled with mixed items of two different types. The types are either

KeyValuePair<Int32, FontFamily>

or

KeyValuePair<Int32, String>

Now there are occasions where I am only interested in the Key of the selected item, which is always an Int32.

What would be the easiest way to access the Key of the selcted item? I am thinking of something like

Int32 key = ((KeyValuepair<Int32, object/T/var/IdontCare>)combobox.SelectedItem).Key;

but that doesn´t work.

So all I have is

    Int32 key;
    if(combobox.SelectedItem.GetType().Equals(typeof(KeyValuePair<Int32, FontFamily)))
    {
        key = ((KeyValuePair<Int32, FontFamily)combobox.SelectedItem).Key;
    }
    else if(combobox.SelectedItem.GetType().Equals(typeof(KeyValuePair<Int32, String)))
    {
        key = ((KeyValuePair<Int32, String)combobox.SelectedItem).Key;
    }

which works, but I wonder if there is a more elegant way?


Solution

  • Casting to dynamic (poor man's reflection) can do the trick

    var key = (int) ((dynamic) comboxbox.SelectedItem).Key);