If I have an object instance and I know it is actually a boxed integer, then I can simply cast it back to int like this:
object o = GetSomethingByName("foo");
int i = (int)o;
However, I don’t actually know that the value is an integer. I only know that it can be assigned to an integer. For example, it could be a byte, and the above code would throw InvalidCastException in that case. Instead I would have to do this:
object o = GetSomethingByName("foo");
int i = (int)(byte)o;
The value could also be a short, or something else which can be assigned to an int. How do I generalize my code to handle all those cases (without handling each possibility separately)?
Simply writing the question made me remember that there is a
Convertclass. This seems to work:edit: but unfortunately, it will also do type conversions that I actually don’t want, like parsing strings.