Reputation: 5024
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
Upvotes: 1
Views: 2334
Reputation: 1500855
I'd use Convert.ToInt32(object)
:
object o = ...; // Boxing...
int? x = o == null ? (int?) null : Convert.ToInt32(o);
Note that when you box an int?
, short?
or byte?
, 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.ToInt32
will 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?
Upvotes: 9