Easy to learn C # boxing and unpacking

Source: Internet
Author: User
First look at what is packing and unpacking?
In simple terms:
Boxing is the conversion of a value type to a reference type;
Unpacking is the conversion of a reference type to a value type.
Value types, including primitive types (Sbyte, Byte, short, Ushort, Int, Uint, Long, Ulong, Char, Float, Double, Bool, Decimal), enumeration (enum), struct (struct).
Reference types include classes, arrays, interfaces, delegates, strings, and so on.

Boxing: An implicit conversion of a value type to a reference type or to any interface type implemented by this value type
For example: int temp = 3;
System.Object obj = temp;
Where temp is the value type, allocated in the stack, and when we assign the reference type of obj, we need to assign an obj object to the heap and assign the temp value to it, so a series of procedures are the boxing process.

Unboxing: Explicit conversions from reference types to arbitrary value types. Unlike boxing, split-box display conversion.
For example: int temp = 3;
System.Object obj = temp;
int i = (int) obj;
During the unpacking process, you first determine that the object obj is a boxed value of a value type, and then assign the value to the value type.
Implicit conversions always succeed without throwing an exception:
(1), from the derived class to the base class;
(2), from the derived interface to the base interface;
(3), from the class to the interface (the class implements the interface);
(4), from null to any class;
Explicit reference conversions, the following may throw an exception, the conversion does not necessarily succeed:
(1), from the base class to the derived class;
(2), from the interface to the interface (the base interface to the derived interface or two interfaces are not related);
(3), from the interface to the class (the class implements the interface or the class is not closed);
(4), from the class to the interface (the class does not implement the interface and the class is not closed);

The definition of unpacking and boxing is briefly described above, and the following is a discussion of how boxing and unpacking are used with heaps and stacks
Where the value type is allocated memory in the stack, the declaration itself is an initialization process, which does not require garbage collection, as long as the defined scope will automatically free memory, and the reference type is allocated in the heap, as in Java, in the heap allocation of memory, and its managed heap garbage collection. Boxing/unpacking occurs when two data types are converted.
Compare the pros and cons of boxing and unpacking
Boxing and unpacking, while satisfying conversions between two types. However, from the boxing process is not difficult to see, each time the box to a new object in the heap, the equivalent of particularly large is sure to greatly affect the efficiency of the program. Things always have two sides, every sword has two sides, things will be simple, performance also down. Therefore, in the application, we should try to avoid the boxing operation.
Knowing the boxing and unpacking operations, we can clearly understand that the boxing operation will cause the data to be copied on the heap and stack, and the frequent boxing operation will lose the performance. In contrast, the unboxing process is relatively small in terms of performance loss.
Detailed steps for packing and unpacking

1. The detailed steps of packing (box):

(1), allocating a memory space on the heap, the size equals the size of the value type object that needs to be boxed plus the members that are owned by the two reference type object: type Object pointer and synchronous block reference.
(2), copy the value type object on the stack to the newly allocated object on the heap.
(3), returns a reference to a new object on the heap, and stores it in an object of that value type that is boxed on the stack.
This step does not need to be written by the programmer, and the compiler automatically adds the IL code that performs the above functions in any place where the boxing occurs.
The so-called unboxing is the concept of boxing, but the unpacking process and boxing is not the reverse is:
2. Detailed steps of unpacking (Unbox.any)
Throws a NullReferenceException exception if the object to be unboxing is null.
Throws a InvalidCastException exception if the reference points to a boxed object that is not a desired object.
(1), get the address of each field in the boxed object, this process is "unpacking"
It is necessary to note that the general unpacking will be accompanied by the object copy, but the copy operation is not the scope of unpacking.

Here are two small examples of how boxing, unpacking, and how to avoid consuming memory due to frequent boxing
(1), Packing:

Using System;   public class Test   {public         static void Main (string[] args)        {            int i = ten;            The I boxing of the value type            //need to be noted: The boxing here takes a copy of the value of            object obj = i;            Check if boxing succeeded            if (obj is int)            {               Console.WriteLine ("Data already boxed!");            }            Here we change the value of I            =;            Console.WriteLine (the value of "int I now is: {0}", i);           Console.WriteLine ("Int I boxed value is: {0}", obj);}    }

(2), unpacking:

int i = ten;    Object obj = i;    int j = (int) obj;    (3), avoid frequent packing:    int i = ten;    int j =;    int s =;    Console.WriteLine ("I has a value of {0},j value of {1},s}", i.ToString (), j.tostring (), s.tostring ());

The above is the introduction of C # Packing and unpacking, the idea is very clear, the content is very comprehensive, including the advantages and disadvantages of boxing and unpacking, packing and unpacking procedures, is suitable for beginners to learn.

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.