Re: conditional operator throws exceptions when casting
- From: "Peter Duniho" <NpOeStPeAdM@xxxxxxxxxxxxxxxx>
- Date: Mon, 03 Dec 2007 09:59:45 -0800
On Mon, 03 Dec 2007 08:47:25 -0800, Webbert <webbertsolutions@xxxxxxxxxxxxxxxxxxxxxxx> wrote:
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
.
- References:
- conditional operator throws exceptions when casting
- From: Webbert
- Re: conditional operator throws exceptions when casting
- From: Jon Skeet [C# MVP]
- conditional operator throws exceptions when casting
- Prev by Date: Re: How to perform XPath queries on HTML?
- Next by Date: Re: System.Diagnostics.Process - Dispose?
- Previous by thread: Re: conditional operator throws exceptions when casting
- Next by thread: Re: conditional operator throws exceptions when casting
- Index(es):
Relevant Pages
|