conversion of value types and boxing

  • Thread starter Thread starter eXavier
  • Start date Start date
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
 
I suppose you could add a conversion from object, and then in the
conversion method check if ( obj is int )



Mattias
 
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
:-(
 
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.
 
Back
Top