If I have an object reference that references a byte?, short? or int?, is there a way to unconditionally cast or convert that object reference to int? without writing separate code for each case?
For example:
byte? aByte = 42; // .. or aByte = null
object anObject = aByte;
//...
var anInt = (int?)anObject //As expected, doesn't work
I’d use
Convert.ToInt32(object):Note that when you box an
int?,short?orbyte?, you always end up with a null reference or a boxed non-nullable value – there’s no such thing as a “boxed nullable value” as such.Convert.ToInt32will work for all the boxed types you’ve mentioned – although it would also work for things like a string “42” etc. Is that a problem?