Understood.
I guess I just don't understand why 0 (zero) is getting boxed to the type of
v before the cast. I would have expected the literal type to be used.
Thanks,
Dave
> > I wrote a little test to demonstrate.
> >
[quoted text clipped - 16 lines]
>
> Change the literal to (Int16)0 and it should be okay.
> Understood.
>
> I guess I just don't understand why 0 (zero) is getting boxed to the
> type of v before the cast. I would have expected the literal type to be
> used.
The literal type is used, just not when you are expecting it to.
The "?:" expression needs to have a single type. The type is generated at
compile time, and if you have two different types in the result operands
for the operator, one needs to be implicitly castable by the compiler to
the type of the other, with the type that winds up being suitable for the
cast being applied to the whole expression.
Since the result operands have type "object" and type "Int32", and because
Int32 is implicitly castable to object but object is not implicitly
castable to Int32, the type of the whole expression is object and the
Int32 parameter must be cast to object before evaluating the expression.
The implicit cast simply boxes the Int32, which of course is cannot be
successfully unboxed to an Int16.
As Jon says, you can resolve the issue by providing an explicit type for
the literal by casting it to Int16. That way when it gets boxed to suit
the expression's overall type, it's a type that can be cast back to Int16.
Pete
Webbert - 03 Dec 2007 20:33 GMT
Jon/Peter,
Thanks for the input.
I have a tendency to want to know why. The underlying piece that I was not
aware of was that the conditional operator needs to have a single type at
compile time. With that in mind I understand exactly why the cast was
failing.
Perfectly clear now.
Thanks,
Dave
> > Understood.
> >
[quoted text clipped - 22 lines]
>
> Pete
Peter Duniho - 03 Dec 2007 20:47 GMT
> Jon/Peter,
>
> Thanks for the input.
>
> I have a tendency to want to know why.
An attitude like that should serve you well. :)
> The underlying piece that I was not
> aware of was that the conditional operator needs to have a single type at
> compile time.
I thought as much. It's a natural requirement IMHO, but not one that's
necessarily obvious at first glance. I've overlooked it myself in the
past. (It does become painfully obvious when the two result operands
cannot be implicitly cast from one to the other, but it's harder to write
code like that by accident. :) )
> With that in mind I understand exactly why the cast was
> failing.
>
> Perfectly clear now.
Excellent. Glad to hear we could help!
Pete