Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# boxing question

First, two examples:

// This works
int foo = 43;
long lFoo = foo;

// This doesn't
object foo = (int)43;
long? nullFoo = foo as long?; // returns null
long lFoo = (long)foo; // throws InvalidCastException
if (foo.GetType() == typeof(int))
    Console.WriteLine("But foo is an int..."); // This gets written out

Now, my guess as to why the second doesn't work is because of boxing. The purpose behind this code is to implement IComparable. I need some way to coerce an object into either a long or a ulong as appropriate, or if it's neither, than to throw an error. I don't want to have to implement checks for each basic numeric type (byte, int, long, ubyte, ...) I'd rather just catch them in the largest numeric type and deal with it that way. Thoughts from all the smart people here? How can I unbox the object, preferably avoiding reflection, but I suppose if that's the only way... Or should I just not implement the non-generics version of IComparable?

Edit:

This seems to work, but seems like a horrible hack around the problem. Is it just me?

long lFoo = long.Parse(foo.ToString());
like image 816
Matthew Scharley Avatar asked Apr 09 '26 05:04

Matthew Scharley


1 Answers

object foo  = (int) 43;
long   lFoo = ((IConvertible) foo).ToInt64(null);
like image 118
Mark Cidade Avatar answered Apr 10 '26 19:04

Mark Cidade



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!