Re: conditional operator throws exceptions when casting

Tech-Archive recommends: Fix windows errors by optimizing your registry



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
.



Relevant Pages

  • Re: how to convert statment
    ... Dim buffer As New Byte ... I am slightly mystified as to why the cast to uint is there in the ... Note that I have left in the perhaps-redundant cast to Int32 ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Cast int to float
    ... ExecuteScalar does NOT return an "Int32". ... So first you need to cast to the correct type. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Casting problem with small int
    ... > Still seems like I shouldn't have to explicitly cast and Int16 to an Int32 ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: What is wrong with this transformation?
    ... derived column transformation. ... Something about casting operands... ... input column or the result of a cast, and cannot be used with the ...
    (microsoft.public.sqlserver.dts)
  • Re: field type convertion error
    ... Specified cast is not valid. ... If I don't do the cast at all (Since it's an Int16 all the way through ... The easiest way to solve these kinds of errors is to place a breakpoint on this row and take a look at the type in the watch window. ...
    (microsoft.public.dotnet.languages.csharp)