Unboxing object containing a value which is known to be assignable to an integer variable

Posted by Wim Coenen on Stack Overflow See other posts from Stack Overflow or by Wim Coenen
Published on 2010-03-04T11:57:04Z Indexed on 2010/03/12 11:07 UTC
Read the original article Hit count: 156

Filed under:

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)?

© Stack Overflow or respective owner

Related posts about c#