Boxing and unboxing in C)

Source: Internet
Author: User

/* Author:. Please indicate the source and author when reprinting */

 

We know that in C #, all types are derived from class objects, and the derived classes and inherited classes can be converted to each other. This introduces the concepts of "Packing" and "unpacking.

Packing: explicitly or implicitly converts a value of a type to the object type, or to an interface inherited by this type. After packing, the value of this object class in the heap area in the memory is a copy of the original type. For example:

Int I = 2;
String STR = "hello ";
Object objstr = STR; // implicit
Object objint = (object) I; // explicitly

Interestingly, you can use obj. tostring () to print the original value after packing. For example, console. writeline (objstr. tostring () displays hello.

Unpacking: explicitly converts the boxed object type to the original type. In this case, the is operator or GetType () can be used to determine the original object type. For example

Int n = (INT) objint;

Int S = (string) objstr;

If (objint is int) console. writeline ("Yeah! ");

If (objstr. GetType (). tostring () = "system. String") console. writeline ("OK ");

Note:

1. If it is not converted to the original type after unpacking, no errors will occur during compilation, but errors will occur during running. Therefore, after unpacking, the conversion type must be correct.

2. When using GetType (). ToString () to judge, use the full name of the type, for example, System. String instead of String.

 

 

 

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.