Boxing conversions for C #

Source: Internet
Author: User

A boxing conversion is the implicit conversion of a value type to an object type, or the conversion of the value type to an interface type applied by the value type (interface-type). Boxing the value of a value type, that is, creating an instance of object and copying that value to this object, for example:

int i=10;
Object obj=i;

Use the following figure to represent the boxing process:

We can also use the explicit method for boxing operations:

int i=10;
Object Obj=object (i);

We can assume that there is a boxing type, and its declaration is as follows:

Class T_box
{
T value;
T_box (Tt) {
value=t;
}//The constructor of this type
}
Here T represents the type of value that will be boxed, it can be int, char, enum, and so on. Now we're going to boxing the value V of type T, which executes the following: Execute new T_box (v), which returns an instance of the result as the value of the object type, and then the statement:

int i=10;
Object obj=i;

Equivalent to:

int i=10;
Object Obj=new Int_box (i); Loading I boxing into object obj

Let's take a look at the following procedure.

Program Listing 4-4:

Using System
class test{public
  static void Main () {
    int i=10;
    Object obj=i; Object Type
    if (obj is int) {
      Console.Write ("The value of ' I is boxing!");
    }
    i=20;  Change the value of I
    Console.WriteLine ("Int:i={0}", i);
    Console.WriteLine ("Object:obj={0}", obj);
    }

The output result is: The

value of I is boxing!
int:i=20;
object:obj=10;

This proves that the value of the boxed type is assigned to the object as a copy.

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.