conversion of value types and boxing


E

eXavier

Hello,
I have class (let's say A) wrapping Int32 type and have added implicit
conversion operators for converting between int and A.
Now I would like to have also explicit operator for conversion from boxed
int to A. This seems to be problem, because I don't know the exact type of
boxed int.

For following code snippet

A a = (A)GetX(3);
....
object GetX(int opCode) { //this method can return different types depending
on value of opCode
...
if (opCode == 3) return new int(5);
}

when returning from GetX(), int value is boxed to object and conversion from
boxed int to A fails with 'Specified cast is not valid' because unboxing
occures first which is by itself implicit conversion. I would have to use
A a = (A)(int)GetX(3);
which is annoying.

I think that the conversion I would like to have is not possible in C#, but
I'd like to be sure. Do you agree with me? Or do you have solution for me?

Thanks,
eXavier
 
Ad

Advertisements

M

Mattias Sjögren

I suppose you could add a conversion from object, and then in the
conversion method check if ( obj is int )



Mattias
 
F

Filip Hurta

I cannot add conversion to object. Conversion operator cannot be added
for conversion between types S, T where S is inherited from T or T is
inherited from S and object is base type of all types, even value types
:-(
 
Ad

Advertisements

G

Guest

I think that the conversion I would like to have is not possible in C#, but
I'd like to be sure. Do you agree with me? Or do you have solution for me?

I think I agree with you.

Unboxing is an explicit conversion and it must be done with the exact type
of the thing in the box. If you have a boxed int, you have to unbox
explicitly with (int), if it is a boxed double, you have to use (double), and
so on.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

how to determine if typ conversion exists? 3
enum with underlying type 1
AND operator with byte operands 2
nullable types 1
using nullable types 1
Round 3
ridiculous 15
String to Progress Bar max value. 4

Top