Why can unboxing only be done for the type that was previously boxed?

9

I've been researching why there are unboxing and boxing , the answers I found say that there are value types in> reference types , for example in non-generic lists ArrayList . So is it correct to say that unboxing / Int32 does the implicit casting of class System.ValueType to System.Object ? That is, from the Int32 structure to the Object class?

So, since% is a structure and they do not support inheritance, is that why unboxing can only be done for the same type?

    
asked by anonymous 17.07.2017 / 00:36

1 answer

9
  

So it's correct to say that unboxing / Int32 does the casting implicit class System.ValueType for System.Object?

ValueType is an abstract class used to give the required infrastructure to the structures, but is not used directly. then this is incorrect.

  

That is, from the Int32 structure to the Object class?

This is correct, depending on the understanding. boxing is to take a object by value and wrap it in a type by reference >, then when an boxing is done, implicit or explicit, what you are doing is creating an object by reference, in this case a Object , and putting the original structure as its value, you copy the structure to the created object and a reference is created for this object.

  

So, since% is a structure and they do not support inheritance, that's why unboxing can only be done for the same type?

I do not know if I understand this, but I do not think boxing does exist because of inheritance, it exists because of the location and semantics of the value's storage.

Unboxing is copying the value of an object by reference to a type by value, and the type of this structure must be compatible to receive what was stored in the object.

Forget Int32 , this is obsolete. If you are reading material that speaks of it it is obsolete too, look for more current thing. Today in C # very little boxing is needed, although some occur without the person realizing why programmers rarely understand the concept completely. If you are using a bad font you will learn everything wrong.

You have a question here on the site that talks about it. There's a confusion about the semantics of boxing .

We've already talked about boxing in Java , which is very similar. Even using type ArayList as an example which is a boxed type of Boolean .

You'll probably want to know more about boolean and struct .

You have an example of boxing in another question . Note that today almost always the examples have no practical relevance.

    
17.07.2017 / 01:05