Example tutorials for boxing and unpacking

Source: Internet
Author: User
Boxing: Value types are "light" than reference types because they are not allocated as objects in the managed heap, are not garbage collected, and are not referenced by pointers. However, there are many times when you need to get a reference to a value type, for example, suppose you want to create a ArrayList object to hold a set of point structures, with the following code: public sealed class Program{public static void Main () { ArrayList a = new ArrayList (); Point P; Assign a point (not allocated in the heap) for (int i = 0; i < i++) {p.x = P.Y = i;//Initialize member A in the value type. ADD (P); Boxing a value type, adding a reference to ArrayList}}} each iteration of the loop initializes a Ponit value Type field and stores the point in ArrayList. But think about what exactly is stored in the ArrayList? Is it the point structure, the address of the point structure, or something completely different? To know the correct answer, you must study ArrayList's Add method to see what type of argument his parameters are defined into. The Add method of this example is prototyped as follows: public virtual int Add (object value); You can see that add is getting an object parameter, that is, add gets a reference to one of the objects on the managed heap as a parameter. But the previous code passed p, which is a point, which is the value type. For the code to work correctly, the point value type must be turned into a real, managed object in the heap, and a reference to the object must be obtained. The boxing mechanism is used to convert a value type to a reference type. Here's what happens when an instance of a value type is boxed: 1, allocating memory in the managed heap. The amount of memory allocated is the amount of memory required for each field of a value type, plus two additional members (type object pointers and synchronous block indexes) that are required for all objects in the managed heap, and the value Type field is copied to the newly allocated heap memory 3, returning the object address. Now the object is an object reference; The value type is a reference type the C # compiler detects that the code above is passing a value type to a method that requires a reference type, so that the object is automatically generated by the code that is boxed. So at run time, the field that currently exists in the point value type instance p is copied to the newly assigned point object. The address of the boxed point object (now the reference type) is returned and passed to the Add method. The point object persists in the heap until it is garbage collected. The point value type variable p can be reused because ArrayList does not know anything about him. In this case, the lifetime of the boxed typeThe lifetime of the boxed value type is exceeded. Unpacking: Suppose you want to use code to get the first element of ArrayList: Point p= a[0]; he gets the reference contained in element 0 of ArrayList, which is placed in the instance p of the point value type. To do this, all the fields in the boxed point object must be copied to the value type variable, which is on the thread stack. The CLR completes the replication in two steps. The first step gets the individual point field addresses in the boxed point object. This process is called unpacking. The second part of the value that the field contains is copied from the heap to the stack-based value type instance, and the unboxing is not reversed directly from the boxing process. Unpacking code is much lower than boxing. Unpacking is actually the process of getting a pointer to the original value type contained in an object. In fact, the pointer is pointing to the unboxed part of the boxed instance. So unlike boxing, tea fragrance does not require copying any bytes in memory, knowing this important difference should also be known after a focus is often immediately followed by a field copy. Boxed value type instances in the unboxing are, internal occurrences of these things: 1, if the variable containing "reference to boxed value type" is null, throws NullReferenceException exception 2, if the referenced object is not a boxed instance of the desired value type, Throw InvalidCastException exception The second means that the code works in a different way than you might think: public static void Main () {Int32 x = 5;object o = x;//boxing on X, o referencing a boxed object Int1 6 y = (Int16) o; Throws an InvalidCastException exception} logically, it is fully able to get the boxed Int32 of the O reference, Cast it to int16. However, when the object is disassembled, it can only be converted to the originally unboxed value type-in this case Int32, the following is the correct wording: public static void Main () {Int32 x = 5;object o = x;//x boxing, o reference the boxed object Int16 y = (Int16) (Int32) O; First unpacking is the right type, then transformation} in the following code: public static void Main () {Point p;p.x = P.y = 1;object o = p;//P boxing, O reference boxed instance//Change the X field of point to 2p = (Po int) O; For o unpacking, copy the field from the boxed instance to the stack variable p.x = 2; Change the state of the stack variable o = p; Boxing p, o referencing the new boxed instance} The last three rowsThe only purpose of the code is to change the X field of point from 1 to 2. To do this, you first perform a unboxing, perform a field copy, change the field (on the stack), and finally execute the boxing (creating a completely new boxed instance on the managed heap). This allows you to see how the boxing unboxing affects the performance of your application. Q: public static void Main () {Int32 v = 5;object o = v;v = 123; Console.WriteLine (v+ "," + (Int32) o);} How many times has the above code been boxed?
Related Article

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.