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?
You certainly don't need to use GetType()
. You could use:
int key;
var item = combobox.SelectedItem;
if (item is KeyValuePair<int, FontFamily>)
{
key = ((KeyValuePair<int, FontFamily>) item).Key;
}
else if (item is KeyValuePair<int, string>)
{
key = ((KeyValuePair<int, string>) item).Key;
}
I don't think there's really a better way without using reflection or dynamic typing, assuming you can't change the type of the selected items to your own equivalent to KeyValuePair
with some non-generic base type or interface.
See more on this question at Stackoverflow