Boxing and unpacking of [CLR via C #] value types

Source: Internet
Author: User

Let's look at a sample code first:

namespaceconsoleapplication1{classProgram {Static voidMain (string[] args) {ArrayList a=NewArrayList ();            Point P;  for(inti =0; I <Ten; i++) {p.x= P.Y =i;            A.add (P);        } console.readkey (); }    }    structPoint { PublicInt32 x, y; }}

In this example, the ArrayList Add method is prototyped as follows:

Public virtual Int32 Add (object value);

As you can see, the Add method needs to get an object type argument, in other words, add needs to get a reference to an object on the managed heap as a parameter. But in the previous code, the parameters of the value type are passed. For the code to work, the point value type must be converted to a real object that is managed in the heap. And you must get a reference to this object.

To convert a value type to a reference type, use a mechanism called boxing. The following summarizes what happens internally when an instance of a value type is boxed.

1) Allocate good memory in the managed heap. The amount of memory allocated is the amount of memory that is required for each field of a value type plus two additional members that are required by all objects of the managed heap.

2) The value type of the field is copied to the newly allocated heap memory.

3) Returns the address of the object.

After you know how the boxing is done, then talk about unpacking.

Point P = (point) a[0];

Now you want to get the reference contained in element 0 of ArrayList and try to place it in instance p of a point value type. To do this, all the fields contained in the boxed point object must be copied to the value type variable p, which is on the thread stack. The CLR completes this copy operation in two steps. The first step is to get the address of each point field in the boxed point object, a process called unpacking. The second step is to copy the values contained in these fields into a stack-based value type instance.

static void Main (string[] args)        {            Int32 x = 5;            Object o = x;            Int16 y = (Int16) o; Throws a InvalidCastException exception

Int16 y = (Int16) (Int32) O; This is the correct notation console.readkey (); }

Logically, it is possible to get a boxed Int32 referenced by O and then cast it to a Int16. However, when unpacking an object, you can only transform it to a value type that was not boxed.

Because the unboxed value type does not have a synchronous block index, you cannot use various methods of the System.Threading.Monitor type (or use the C # lock statement) to have multiple threads synchronize access to this instance.

Although unboxed value types do not have type object pointers, virtual methods that are inherited or overridden by a type (such as equals, GetHashCode, or ToString) can still be called. The value types used to call virtual methods are not boxed. However, if you override the virtual method to invoke the implementation of the method in the base class, the value type instance is boxed when the implementation of the base class is called. However, when calling a non-virtual, inherited method (such as GetType or MemberwiseClone), the value type is boxed anyway. This is because these methods are defined by System.Object, so these methods expect the this argument to point to a pointer to an object on the heap. Dividing an unboxed instance of a value type into an interface of a type requires that the instance be boxed. This is because the interface variable must contain a reference to an object on the heap.

Boxing and unpacking of [CLR via C #] value types

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.