Why does this work:
ComboBox cb = sender as ComboBox;
int validSelection = Convert.ToInt32(cb.Tag);
if (cb.SelectedIndex != validSelection) {
cb.SelectedIndex = validSelection;
}
…but this:
ComboBox cb = sender as ComboBox;
int validSelection = (int)cb.Tag; // <-- fails
if (cb.SelectedIndex != validSelection) {
cb.SelectedIndex = validSelection;
}
…errors out with “Object not set to a reference of an object”?
That’s because a conversion is not the same thing as a cast.
cb.Tagis probably astring, not anint, and one is not directly convertible to the other.Convert.ToInt32()actually parses thestringand creates a newintwith the converted value.Casts only try to interpret an instance of a type as an instance of another type.