Boxing & unboxing

Source: Internet
Author: User

Boxing & unboxing]

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. when the CLR boxes a value type, it wraps the value inside a system. object and stores it on the managed heap. unboxing extracts the value type from the object. boxing is implicit; unboxing is explicit. the concept of boxing and unboxing underlies the C # uniied view of the type system in which a value of any type can be treated as an object.

int i = 123;// The following line boxes i.object o = i;  o = 123;i = (int)o;  // unboxing
View code

In relation to simple assignments, boxing and unboxing are computationally expensive processes. when a value type is boxed, a new object must be allocated and constructed. to a lesser degree, the cast required for unboxing is also expensive computationally. for more information, see performance.

Unboxing can only correspond to the same type; otherwise, an error occurs, as shown in the following example:

class TestUnboxing{    static void Main()    {        int i = 123;        object o = i;  // implicit boxing        try        {            int j = (short)o;  // attempt to unbox            System.Console.WriteLine("Unboxing OK.");        }        catch (System.InvalidCastException e)        {            System.Console.WriteLine("{0} Error: Incorrect unboxing.", e.Message);        }    }}
View code

Reference: http://msdn.microsoft.com/zh-cn/library/yz2be5wk.aspx

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.