Could you tell me why an explicit downcast of a numeric object (without prior upcast) is available only to an int, applying to other data types gives an invalidCastException error. With a preliminary upcast, everything is clear, but I expected that without a preliminary upcast, a downcast would not work.

Update. As corrected - we are talking about boxing / unboxing, and not about the downcast.

  • it all depends on what is stored in this object . If there is no int you will get the same error. - Grundy
  • @Grundy stores a numeric value, for example 5. It is in the range of all numeric data types. - Sparkll

1 answer 1

Conversions to object and back are called packaging and unpacking .

The peculiarity of unpacking value-types is that you cannot unpack one value-type into another.

In this case, since int is already stored in object , it cannot be unpacked into another structure.

  • Yes, I did not put it correctly, this is not a downcast / upcast, but boxing / unboxing. The particularities of value types during packing and subsequent unpacking are understandable, here the reduction is only to the original type. But it seems that by writing a number in object, it can only be unpacked into an int. Although it seemed to me that it shouldn’t work at all without pre-packing - Sparkll
  • 3
    @Sparkll, no, it all depends on what kind of number you write down. If your code is just object o = 5 , then you explicitly write int , because any number without indication is considered an int type, but if you write a long literal: object o = 5L , then you can unpack it only in long - Grundy
  • Yes, thanks, literally now he himself came to this. now everything was clarified - Sparkll
  • 2
    You can add a link to habr in your answer, an interesting article was dug up by habr.com/post/239219 - Sparkll
  • @Sparkll, I have already added to the article in msdn, in which this is all described :) especially the article is quite old already - Grundy