C # boxing and unboxing ),

Source: Internet
Author: User
Tags mscorlib unpack

C # boxing and unboxing ),
Directory:

 

1. packing and unpacking

2. deep understanding of packing and unpacking

3. int [] to object [], conversion from an array of value types to an array of Objects

4. Use generics to reduce packing and unpacking

1. packing and unpacking
 

PackingConvert "Value Type" to "reference type ";

UnpackConverts a "reference type" to a "value type ";

First, we need to understand why packing and unpacking are required. All types of C #, including int and boo, are inherited from System. Object, but there are values and reference types. Now you have to ask, int is inherited from the object type and object is the reference type. Why is int not a reference type but a value type? This involves the concepts of packing and unpacking.

We know that the object is created on the stack, and its creation and destruction will inevitably lead to additional CPU and memory consumption. If you place tiny and commonly used data types such as int and boo on the heap for creation and destruction, the performance of the language will be greatly limited, sometimes even intolerable. C # Separate the value type from the reference type. The value type is directly created in the stack and destroyed directly after the scope is exceeded. When a value type is required to become an object, use the packing operation to change the value type to a reference type object. In this way, we can use the object as a universal interface to unify all types in the language.

UnpackWhich of the following statements is used in the official MSDN document?Unboxing.In fact, unpacking is the inverse operation of packing, that is to say, we only perform the unpacking operation on the reference type (usually the object) that has been packed in the box. The consequences of the simple unpacking operation cannot be imagined.

Packing and unpacking are the core concepts of C #. C # uses it to unify the type system. With packing, any type of value can be considered as an object. When packing, CLR packs the value type into the System. Object and then stores it on the managed stack. The value type is extracted from the object. Packing is implicit while unpacking is displayed.

// Bind boxingint I = 3; // allocate the object o = I on the stack; // implicit binning operation, int I on the stack object B = (object) I; // display the binning operation // unboxingint j = (int) o; // display the binning (the object o is split into int type) int k = B; // error !!, You cannot unpack it implicitly.

UnpackOperations include

1. Check the object instance to make sure it is a boxed value of the given value type.

2. Copy the value from the instance to the value type variable.

 

Let's take a look at this example:

int i=0;System.Object obj=i;Console.WriteLine(i+","+(int)obj);

Three packing and one unpacking occurred in total! ^ _ ^. Can you see it ?!
The first is to pack I, and the second is to convert I to the string type when the output is made. The string type is the reference type, that is, the packing is made, and the third packing is (int) convert obj to string type, boxed!
Split the box is (int) obj, split the obj !! 2. deep understanding of packing and unpacking

object o = 1 ;

The IL code for this sentence is as follows:

. Locals init ([0] object objValue) // the above three lines of IL indicate the local variable IL_0000: nop IL_0001: ldc that declares the object type as objValue. i4.s 1 // place integer 1 to the top of the stack IL_0003: box [mscorlib] System. int32 // execute the IL box command and apply for System in the memory heap. the heap space IL_0008: stloc.0 required by Int32 // The variables on the stack Are popped up and stored in a local variable with an index of 0.

 

Note the comments. When packing, it is inevitable to apply for memory space on the stack and copy the value type data on the stack to the requested heap memory space, this must consume memory and cpu resources.

object objValue = 4;int value = (int)objValue;

Similarly, let's look at the IL code:

. Locals init ([0] object objValue, [1] int32 'value') // The above IL declares two partial variables: object-type objValue and int32-type value variables IL_0000: nop IL_0001: ldc. i4.4 // press integer 4 into the stack IL_0002: box [mscorlib] System. int32 // execute the IL box command and apply for System in the memory heap. int32 requires the heap space IL_0007: stloc.0 // The variables on the stack Are popped up and stored in the local variable with the index 0 IL_0008: ldloc.0 // press the local variable with the index 0 (that is, the objValue variable) into the stack IL_0009: unbox. any [mscorlib] System. int32 // execute the IL command unbox. any converts an object of the reference type to System. int32 type IL_000e: stloc.1 // store the data on the stack to the local variable whose index is 1, that is, value.

 

The binning operation is opposite to the packing operation. It is used to convert the reference type value stored on the stack to the value type and give the value type variable. The packing and unpacking operations require additional cpu and memory resources. Therefore, a generic type is introduced after c #2.0 to reduce the consumption of packing and unpacking operations. 3. int [] to object [], conversion from an array of value types to an array of Objects

We cannot directly assign values to the object array. For example:

Int [] array = new int [] {0}; object [] oiArray = (object []) array; // error !! Int [] cannot be converted to object []
 string[] a={"1","2","3"};
Object [] osArray = a; // correct. a is a reference type array, which does not contain packing or unpacking.

(Object []) a cannot convert all value type objects of a to the reference type, so the compiler will not use this conversion. The following methods can be used to achieve the goal:

Int [] array = new int [] {0}; object [] oArray = new object [array. length]; for (int I = 0; I <array. length; I ++) {oArray [I] = array [I]; // implicit packing}

 

4. Use generics to reduce packing and unpacking

Sometimes it is said that the use of generic type can improve the performance of the C # program. Some performance improvements are caused by reduced packing and unpacking. Evaluate the following code:

public class Test{    object _o  ;        public Test(object o)    {_o = o ;    }}public class Test<T>{    T _o ;    public Test(T o)    {        _o = o ;    }}

The first Test class does not use generics. If you pass an int type value to Test, multiple packing and unpacking operations are triggered. The type of generic classes has been clarified during instantiation, so there will be no packing or unpacking operations during the copy operation.

 

Reference:

1. yukai http://www.cnblogs.com/yukaizhao/archive/2011/10/18/csharp_box_unbox_1.html

2. MSDN https://msdn.microsoft.com/zh-cn/library/yz2be5wk.aspx.

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.