An Unboxing object containing a value that is known to be assigned to an integer variable

If I have an instance of object , and I know that it is actually a boxed integer, then I can simply return it back to int as follows:

 object o = GetSomethingByName("foo"); int i = (int)o; 

However, I really do not know that this 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 will throw an InvalidCastException in this case. Instead, I would have to do this:

 object o = GetSomethingByName("foo"); int i = (int)(byte)o; 

The value can also be short or something else that can be assigned to int . How to generalize my code to handle all of these cases (without processing each feature separately)?

+4
source share
2 answers

Just writing a question made me remember that there is a Convert class. This seems to work:

 int i = Convert.ToInt32(o); 

edit : but, unfortunately, it will also do type conversions that I really don't want, such as syntax strings.

+5
source

It is interesting to see how Convert.ToInt32 performs the conversion:

  public static int ToInt32(object value) { return value == null? 0: ((IConvertible)value).ToInt32(null); } 

The trick is to pass an object to IConvertible .

+2
source

Source: https://habr.com/ru/post/1303111/


All Articles