I´m working on a ComboBox derived class which could be able (under some circumstances) to add a "special" item to it DataSource source. The code is as follows
protected void InsertSpecial()
{
// source is a List<T> protected field or property of the derived class
object item = source[0];
comboItemType = item.GetType();
if (comboItemType == null || comboItemType.IsClass == false)
return;
whereProperty = comboItemType.GetProperty(comboBox1.DisplayMember,
BindingFlags.Public | BindingFlags.Instance);
if (whereProperty == null)
return;
object special = Activator.CreateInstance(comboItemType);
if (special == null)
return;
whereProperty.SetValue(special, "<special>", null);
object result = Convert.ChangeType(special, comboItemType);
MessageBox.Show(String.Format( "{0} {1}", result.GetType().ToString(), whereProperty.GetValue(result, null)) );
// here, the compiler throw an error telling result is an invalid argument
source.Insert(0, result);
}
All the code works ok in this agnostic mode, until the time to insert the new object in the list. Even after the Convert.ChangeType call (the MessgeBox shows the expected type). How can I cast the result object to the List<>´s expected type? TIA