Boris B.
Boris B.

Reputation: 5024

.Net - Cast or convert a boxed byte?, short? or int? to int?

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

Answers (2)

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56172

var i = (anObject as IConvertible).ToInt32(null);

Upvotes: 1

Jon Skeet
Jon Skeet

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

Related Questions