<p>Is there a way to test if an object is a dictionary?</p>

<p>In a method I'm trying to get a value from a selected item in a list box.  In some circumstances, the list box might be bound to a dictionary, but this isn't known at compile time.</p>

<p>I would like to do something similar to this:</p>

<pre><code>if (listBox.ItemsSource is Dictionary&lt;??&gt;)
{
    KeyValuePair&lt;??&gt; pair = (KeyValuePair&lt;??&gt;)listBox.SelectedItem;
    object value = pair.Value;
}
</code></pre>

<p>Is there a way to do this dynamically at runtime using reflection?  I know it's possible to use reflection with generic types and determine the key/value parameters, but I'm not sure if there's a way to do the rest after those values are retrieved.</p>

Check to see if it implements IDictionary.
See the definition of System.Collections.IDictionary to see what that gives you.
```
```
if (listBox.ItemsSource is IDictionary)
{
    DictionaryEntry pair = (DictionaryEntry)listBox.SelectedItem;
    object value = pair.Value;
}
```
```
EDIT:
Alternative when I realized KeyValuePair's aren't castable to DictionaryEntry
```
```
if (listBox.DataSource is IDictionary)
{
     listBox.ValueMember = "Value";
     object value = listBox.SelectedValue;
     listBox.ValueMember = ""; //If you need it to generally be empty.
}
```
```
This solution uses reflection, but in this case you don't have to do the grunt work, ListBox does it for you. Also if you generally have dictionaries as data sources you may be able to avoid reseting ValueMember all of the time.