Unboxing object containing a value which is known to be assignable to an integer variable
- by Wim Coenen
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)?