Why can Unboxing only be made for the type that was previously performed Boxing?

Asked

Viewed 94 times

9

I’ve been searching for why there is Unboxing and Boxing, the answers I found say there is to value types have the same behaviour as Reference types, for example on non-generic lists ArrayList. So it’s correct to say that the Unboxing/Int32 does the casting implicit class System.ValueType for System.Object? That is, of the structure Int32 for the class Object?

So, why Int32 be a structure and they do not support inheritance, that’s why Unboxing can only be made for the same type?

1 answer

9


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

ValueType is a class abstract used to give the necessary infrastructure to the structures, but is not used directly, so this is incorrect.

That is, of the structure Int32 for the class Object?

This is correct, depending on the understanding. The Boxing is just catch a object by value and box it in a type by reference, then at the moment it is made a Boxing, implicit or explicit, what you are doing is creating an object by reference, in this case a Object, and placing as its value the original structure, that is, copies the structure to the created object and a reference is created for this object.

So, why Int32 be a structure and they do not support inheritance, that’s why the Unboxing can only be made for the same type?

I don’t know if I understand that, but I don’t think, Boxing does not exist because of heritage, exists because of local and semantic value storage.

The Unboxing is to copy 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 ArrayList, is obsolete. If you are reading material that speaks of it it is obsolete too, look for something more current. Today in C# very little Boxing is necessary, although some occur without the person realizing because programmers rarely understand the concept at all. If you’re using a bad font you’ll learn it all wrong.

There is a question here on the website that talks about it. There is a confusion about the semantics of Boxing.

We’ve already talked about the Boxing java which is very similar. Including using the guy Boolean as an example that is a boxed type of boolean.

You probably want to know more about struct and class.

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

  • Oops, I meant System.Valuetype for Sytem.Object, my mistake

Browser other questions tagged

You are not signed in. Login or sign up in order to post.