C # Unpacking and boxing

Source: Internet
Author: User

Net Is divided into two types, one is a value type, and the other is a reference type. The essential difference between these two types is that the value type data is allocated on the stack, while the reference type data is allocated on the heap. Then, if you want to put a value type data on the heap, you need a boxing operation, conversely, a value type data placed on the heap is taken out, you need to do the unpacking operation.

For example, for the following simple boxing and unboxing action statements.

int i = 123;

Object obj = i;//boxing

if (obj is int)

int j = (int) obj;//unboxing

for better interpretation of boxing and unpacking operations, I borrowed MSDN 's explanatory diagram on "Boxing", as follows.  

Understand the meaning of these two words, now say why to reduce the packing and unpacking operations.

There are two reasons, mainly about efficiency: one is that the operation of the heap is less efficient, and the other is that for the memory resources allocated on the heap, the GC to recover, thereby reducing program efficiency.

Considering these two factors, it is necessary to reduce the packing and unpacking operations in the program.

How to reduce that involves more of these two operations, the format output operation, for example:String.Format,Console.WriteLine and the like statements.

For example:

Console.WriteLine ("Number List:{0}, {1}, {2}",

(a);

For "1,2,3", the equivalent of the previous "123", need to go through boxing and unpacking two operations. So how to avoid, in fact, just pass the reference type data to WriteLine , that is, the following way.

Console.WriteLine ("Number List:{0}, {1}, {2}",

1.ToString (), 2.ToString (), 3.ToString ());

because " The result of 1.ToString () "is a String type, which belongs to a reference type and therefore does not involve boxing and unboxing operations.

second, there are more cases involving boxing and unpacking operations in the collection, such as: ArrayList or HashTable or something.

Potential errors may occur when you put value type data into the collection. For example:

public struct person

{

private string _name;

public string Name

{

get{return _name;}

set{_name = value;}

}

Public person (string personname)

{

_name = PersonName;

}

public override string ToString ()

{

return _name;

}

}

Using the person in a collection

ArrayList arrpersons = new ArrayList ();

Person p = new person ("oldname");

Arrpersons.add (P);

Try to change the name

p = (person) arrpersons[0];

P.name = "NewName";

Debug.WriteLine ((person) arrpersons[0]). Name);//it ' s "oldname"

One might say, is it possible to modify it in the following way?

(person) arrpersons[0]). Name = "NewName";//can ' t be compiled

Unfortunately, the above operation cannot be compiled. for what, for " (person) arrpersons[0]) ", the system uses a temporary variable to receive the value type data after unpacking, so because the value type is allocated on the stack, the operation is for entity operations, but the system does not allow modifications to a temporary value type data.

Using the person in a collection

ArrayList arrpersons = new ArrayList ();

Person p = new person ("oldname");

Arrpersons.add (P);

Try to change the name

p = (person) arrpersons[0];

P.name = "NewName";

arrpersons.removeat (0);//remove old data first

Arrpersons.insert (0, p);//add new data

Debug.WriteLine ((person) arrpersons[0]). Name);//it ' s "NewName"

In fact, this will result in excessive boxing and unpacking operations. A better approach can be accomplished through an interface, which reduces boxing and unpacking operations. The interface implementation for this example should be as follows.

public interface Ipersonname

{

String name{Get;set;}

}

Public struct Person:ipersonname

{

private string _name;

public string Name

{

get{return _name;}

set{_name = value;}

}

Public person (string personname)

{

_name = PersonName;

}

Public override String ToString ()

{

return _name;

}

}

Using the person in a collection

ArrayList arrpersons = new ArrayList ();

Person p = new person ("oldname");

Arrpersons.add (P);

Change the name

((Ipersonname) arrpersons[0]). Name = "NewName";

Debug.WriteLine ((person) arrpersons[0]). Name);//it ' s "NewName"

Many people ask why value types cannot be modified, that is,

(person) arrpersons[0]). Name = "NewName";//can ' t be compiled

And the interface type above can be modified, i.e.

((Ipersonname) arrpersons[0]). Name = "NewName";

This is due to the fact that the type of the temporary variable produced is different, the former is explained earlier, the latter due to the type of temporary variable is ipersonname , which is a reference type, the equivalent of a temporary variable is a reference to the original object, so it is possible to modify it directly to the original object. It can be said that the difference is in itself the type of temporary objects, resulting in an essential difference.

through the interface to rewrite, this reduces the boxing and unpacking operations, but also ensure the correctness of the modification. Note, however, that the interface is for reference types, and if the interface accesses or returns a value type, then the interface can be implemented, but there is no reduction in boxing and unboxing operations.

For boxing and unpacking operations, basically, just remember that frequent boxing and unpacking operations can reduce the efficiency of the program, so you should try to avoid it when writing.

C # Unpacking and boxing

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.